Dizzy
Dizzy

Reputation: 43

Problem with negativ lookbehind in RegEx and multiple digit numbers

I´m fairly new to RegEx.

I have a expression to find one or multiple digit numbers followed by X and one of a specific character.

\d+X[!l1IL]

so i can find 2x! oder 22x1

but if there is a >> in front, i dont want it. i tryed to do negativ lookbehind like

(?<!>>)\d+X[!l1IL]

and it worked if i have a single digit number in front of the X like >>2X1 but it stoped workin if there are multiple digit numbers in between like >>222X1 and i dont get why.

Upvotes: 2

Views: 71

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

There are a couple of solutions depending on what match boundaries you have and also depending on regex flavor:

\b(?<!>>)\d+X[!l1IL]
(?<!>>|\d)\d+X[!l1IL]
(?<!>>)(?<!\d)\d+X[!l1IL]

The regexps mean

  • \b(?<!>>) - match a word boundary and then make sure there is no >> immediately to the left of the current position
  • (?<!>>|\d) - immediately to the left, there must be no >> and any digit
  • (?<!>>)(?<!\d) - the same as above, but the lookbehind is split into two since the lengths of the alternatives differ.

Upvotes: 1

Related Questions