0

I have the following regex so far:

printf "this is (test.com)\n" | grep -Po '(?<=\().*(?=\))'

The above regex will print the desired output, which is test.com

As far as I am adding new parenthesis to my code

printf "this is (test.com) and (alex)\n" | grep -Po '(?<=\().*(?=\))'

, it displays something like:

test.com) and (alex

I would like my regex to print anything between brackets (no matter how many there are). More, I would like to add a condition to print just words between brackets with a specific length.

Eg: (aaa) test1 (bbb) test test (ccc) test (example) (ddd)

I just want printed out the words between brackets that have length 3. So the output should be:

aaa bbb ccc ddd

  • 1
    Use [^)] instead . or if you already use -P (pcre regex) to prohibit regex be greedy you should add ? after *: grep -Po '(?<=\().*?(?=\))' – Costas Feb 11 '15 at 20:51
  • That worked. What about the lenght condition ? Where should I place it, and how ... in order to print words with only 3 characters ? – яүυк Feb 11 '15 at 20:55
  • You have to study quantificator thoroughly. Three characters can be choised like ... (any 3 symbols) or, for example \w{3} (any 3 alphanumeric symbols) – Costas Feb 11 '15 at 21:05
1

Please be noted that expression try to choice the pattern of maximum length (gready regex) match. As you see in your example (regex: symbols between parenthesis) have choiced

  • ...is ( test.com) and (alex )

instead of

  • ...is (test.com) and (alex).

There are two ways to override such behavior:

  1. Substitute any symbol by revers match of limit or devide symbol (for example: (.*) by ([^)]*)
  2. Modern regular expressions (PCRE for example) allow a quantifier to be specified as lazy. They put a question mark after the quantifier to make it lazy .*?. By using a lazy quantifier, the expression tries the minimal match first.

More over the first variant allows to some simplify regex: grep -Po '\(\K[^)]*'

  • Thank you for your response. I would vote this up but I don't have the necessary rep. Supposing that between paranthesis are just letters, it would be easier to add a length condition ? – яүυк Feb 11 '15 at 21:48
  • Try to indicate the exact term for expression: Output words in parenthesis which consist in 3 letter only. Is it correct? '\(\K\w\w\w(?=\))' or '\(\K\w{3}(?=\))' – Costas Feb 11 '15 at 21:55
  • It worked. Thank you for your time. I will look into these so that I will have a better understanding into regex conditions – яүυк Feb 11 '15 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.