varnie
varnie

Reputation: 2595

Regex: match everything the other regex left

I am struggling with the following issue: say there's a regex 1 and there's regex 2 which should match everything the regex 1 does not.

Let's have the regex 1: /\$\d+/ (i.e. the dollar sign followed by any amount of digits.

Having a string like foo$12___bar___$34wilma buzz it detects $12 and $34.

How does the regex 2 should look in order to match the remained parts of the aforementioned string, i.e. foo, ___bar___ and wilma buzz? In other words it should pick up all the "remained" chunks of the source string.

Upvotes: 3

Views: 680

Answers (3)

Nick Reed
Nick Reed

Reputation: 5059

It was tricky to get this working, but this regex will match everything besides \$\d+ for you. EDIT: no longer erroneously matches $44$444 or similar.

(?!\$\d+)(.+?)\$\d+|\$\d+|(?!\$\d+)(.+)

Breakdown


(?!\$\d+)(.+?)\$\d+
(?!     )                   negative lookahead: assert the following string does not match
   \$\d+                    your pattern - can be replaced with another pattern
         (.+?)              match at least one symbol, as few as possible
              \$\d+         non-capturing match your pattern

OR

\$\d+                       non-capturing group: matches one instance of your pattern

OR

(?!\$\d+)(.+)
(?!\$\d+)                   negative lookahead to not match your pattern
         (.+)              match at least one symbol, as few as possible


GENERIC FORM
(?!<pattern>)(.+?)<pattern>|<pattern>|(?!<pattern>)(.+)

By replacing <pattern>, you can match anything that doesn't match your pattern. Here's one that matches your pattern, and here's an example of arbitrary pattern (un)matching.

Good luck!

Upvotes: 0

s.3.valkov
s.3.valkov

Reputation: 75

Try this one

[a-zA-Z_]+ 

Or even better

[^\$\d]+ -> With the ^symbol you can negotiate the search like ! in the java -> not equal

Upvotes: -2

anubhava
anubhava

Reputation: 784958

You may use String#split to split on given regex and get remaining substrings in an array:

String[] arr = str.split( "\\$\\d+" );

//=> ["foo", "___bar___", "wilma buzz"]

RegEx Demo

Upvotes: 4

Related Questions