0

I have the following string:

CHECKING % x j1 (test1^3) @ phi=0 j2 (test2/3) @ phi=1 j3 @ phi=2 j1 (test1^3) @ phi=2 j2 (test2/3) @ phi=3 j3 @ phi=5
CHECKING % x ab (test1^3) @ phi=0 cde (test2/3) @ phi=1 fg @ phi=2 hij (test1^3) @ phi=2 kl (test2/3) @ phi=3 mn @ phi=5

I would like to get all the j1, j2 and j3 as well as the ab, cde ... so everything in front of the brackets or the @ sign respectively, but somehow I cannot make it work. Does someone have an idea for a regex?

Here is what I have tried:

([a-zA-Z_]+[0-9]{0,4})\s+\(.{0,9}\)\s+\@

which gives:

j1 j2 j1 j2 ... ab cde hij kl

But it does not match the j3, fg and mn, how can I include the (...) term only if appearing?

Guiste
  • 449
  • 1
  • 5
  • 16

2 Answers2

1

Building on your original pattern, you can make the part in brackets optional to capture cases without a formula:

([a-zA-Z_]+[0-9]{0,4})\s+(?:\(.{0,9}\))?\s*\@

Demo

wp78de
  • 18,207
  • 7
  • 43
  • 71
  • Awesome, exactly this optional thing I was looking for. So the (?:Something) makes Something optional? What does the ? after the brackets do? – Guiste Apr 12 '18 at 04:08
  • 1
    (?:) is a [non-capturing group](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-what-does-do). The crucial part, however, is the `?` mark after the group, which makes it optional. Also note the following whitespace `\s*`which has a star quantifier (zero or more times), and therefore also optional. – wp78de Apr 12 '18 at 04:14
0

An alternative would be:

\w+(?= \()|\w+(?= @)

This looks for words followed by \s( or followed by \s@.

builder-7000
  • 7,131
  • 3
  • 19
  • 43