Skip to content
Advertisement

regex riddle. want results: ‘onetwothree’, ‘onetwo’, ‘twothree’ but NOT ‘two’. Positive lookahead maybe?. For currency extraction

confused with some basic regex logic. Using simple example:

JavaScript

I want regex to catch:

JavaScript

but NOT

JavaScript

and catching in groups (one)(two)(three).

I know I can use positive lookahead on ‘two’ so that it is only preceded by ‘one’:

JavaScript

but then I cannot get the ‘twothree’ result

The real world need is for currency:

JavaScript

so I want to get these results:

JavaScript

but NOT

JavaScript

help appreciated!

PS need matches in groups (one)(two)(three) or (one)(two) or (two)(three).

Advertisement

Answer

Here’s a pure regex response:

JavaScript

Using conditionals, you can check to see if the first group matched, and if it did, then you can make the last group mandatory.

JavaScript

With this, we just make the first result be optional, so if we match ONE, then THREE is optional. If we miss ONE, then THREE is mandatory.

JavaScript

Try it online!

Read more about conditional regex patterns in PHP here.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement