Home > Enterprise >  Put together Lookbehind and Lookahead
Put together Lookbehind and Lookahead

Time:01-10

I don't understand how to combine lookahead and lookbehind yet. Does somebody have examples so I can try to understand how they work?

my regex:

(?<=\/|\n)[0-9 ]*

input:

544/555/716  \n
Black/Black Black  \n
100/380/236 PCS  

expect output 1:

100 380 236

(last line, numeric only)

https://regex101.com/r/vuva70/1 I want

Match 1: 100
Match 2: 380
Match 3: 236

expect output 2:

544 555 716

Match 1: 544 Match 2: 555 Match 3: 716 (first line, split by slash, numeric only) Thanks for your help!

CodePudding user response:

You do not need to combine them for this case. Get all groups of digits that do not have a newline after them:

(\d )(?!.*\n)

EDIT: For the first line, it gets more difficult, since you have to use different techniques depending on which engine you are using. For example, in some JavaScript engines, you can use a similar technique using lookbehind; but most regex engines do not support variable-length lookbehind. You used PCRE setting in your regex101 examples; for PCRE, you can use \G last-match anchor like this:

(?:^|\G)[^\n]*?\K(\d )

However, this borders on abusing regex. If possible, I would prefer to split the string into lines then split lines by slash, without use of regex.

  • Related