RegEx match pattern within a line only if line begins with a specific criteria

Viewed 50

How do I match a pattern within a line, only if line begins with a specific criteria?

For example, say we'd like to match a 6-digit number on lines with begin only with Banana

Banana lmasfh asfjhas jhona uh3 a y u3u3 303303 ajksdfkas 3jk5hk

Banana lmasfh asfjhas jhona uh3 a y u3u3 202202 ajksdfkas 3jk5hk

Apple lmasfh asfjhas jhona uh3 a y u3u3 101101 ajksdfkas 3jk5hk

From above, the result should be 303303 and 202202 only.

I tried looking into positive lookbehind but they're of fixed width and couldn't proceed. Something like: (?<=^Banana)\d{6}

2 Answers

You're pretty close. There is just "stuff" (which is easily handled with .* in regex) in between. Then add a match group and there you go.

(?<=^Banana).*(\d{6})

Will put both 303303 and 202202 into match group one. Demo: https://regex101.com/r/k87i7x/1

You could leave out the lookbehind and match it instead, and add word boundaries \b to prevent partial matches:

^Banana\b.*\b(\d{6})\b

Regex demo

Related