Multiple regex lookbehind

53 Views Asked by At

I am searching for a string which has several occurrences of other string/char before it:

this is not real example, but it describes what I want to capture - string that occurs right after second (or third, the expression must be scalable and configurable) occurrence of the ":" character.

boo+foo:qoo+loo:thisIsWhatIneed...

Obviously, the following did not work:

(?<=\:){2,}.*

and this would be pretty much opposite (inverted) of what I want:

.*:.*:

enter image description here

4

There are 4 best solutions below

2
Pruss On BEST ANSWER

This will match what you needed from your example:

[^:]*:[^:]*:(.*)

ignored:ignored:captured as group 1

This will let you specify the number of colon delimited words to ignore more easily:

(?:[^:]*:){2}(.*)

This will capture everything after the last colon until the end, regardless of how many colons there are:

:([^:]*)$

regex test website showing results

0
dawg On

If you want to capture something after some fixed number of : then somthing along these lines is your best bet:

/^(?:[^:]+:){2}([^:]*)/

Demo

If you want something after ALL colons, like the last field of some line delimited by : than you can do:

/([^:]*$)/

Demo

In both cases you are essentially 'counting colons' from the front or the back of the string; if from the front, use ^ and $ from the back.

0
InSync On

Instead of lookbehinds, why not a lookahead?

(?<=\:)        # Match something follows a ':'
(?!            # that is not
  \w+\+\w+     # two "words" separated by a '+'
  (?::|$)      # followed by either another ':' or the end of string.
)              # 
.*             # 

Try it on regex101.com.

0
Reilas On

"... I want to capture - string that occurs right after second ... occurrence of the ":" character. ...

A capture group would be a logical approach here.

:.+:(.+)

Attempting to match only the text, utilizing a positive look-behind, typically requires a fixed-length.
Although, some regex engine's allow for variable-length look-behind's—i.e., JavaScript and .NET.

If you're using either of those, you can use the following pattern.

(?<=:.*:).+

var s = 'boo+foo:qoo+loo:thisIsWhatIneed...'
console.log(s.match(/(?<=:.*:).+/))