Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positive lookahead doesn't stop at first occurrence

Tags:

regex

ruby

I use the regex

(?<=Charset:\s).+(?=<br\/>) 

on the following data (There is no newline char in the data, I made it look better) to capture the Charset string

<div class="box_t">Parameters</div>
<div class="box_c">Charset: i763zLFYKBqVs@nZ8PyO}N9<br/>
Input Base: 23<br/>Solution Base: 19<br/>
Timelimit: 3.1416 seconds<br/></div>

However, my match ended up being

i763zLFYKBqVs@nZ8PyO}N9<br/>
Input Base: 23<br/>
Solution Base: 19<br/>
Timelimit: 3.1416 seconds

It seems that the positive lookahead did not stop after the first occurrence. Is there a way to make it stop?

like image 633
Flmhdfj Avatar asked Feb 27 '14 10:02

Flmhdfj


People also ask

What does positive lookahead mean?

Positive lookahead: (?= «pattern») matches if pattern matches what comes after the current location in the input string. Negative lookahead: (?! «pattern») matches if pattern does not match what comes after the current location in the input string.

What is a positive Lookbehind in regex?

Positive lookbehind is syntaxed like (? <=a)something which can be used along with any regex parameter. The above phrase matches any "something" word that is preceded by an "a" word. Negative Lookbehind is syntaxed like (? <!a)something which is used to match a "something" word that is not preceded by an "a".

How do you use positive lookahead?

The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign. You can use any regular expression inside the lookahead (but not lookbehind, as explained below). Any valid regular expression can be used inside the lookahead.

What is a negative Lookbehind?

A negative lookbehind assertion asserts true if the pattern inside the lookbehind is not matched.


1 Answers

An easy way is to use the non-greedy operator.

(?<=Charset:\s).+?(?=<br\/>)
like image 155
sawa Avatar answered Oct 19 '22 23:10

sawa