benjiherb
benjiherb

Reputation: 9

Regex for specific word (starting with 1 letter and ending in numbers) after a positive lookbehind

Apologies if this is a basic question; I'm fairly new to regex and I have done a lot of googling, and I am still stuck on this expression.

I'm trying to capture a word, which starts with a letter and ends with digits. I am using a positive lookbehind since this word always occurs after a specific. However, there can sometimes be other words in between these 2, and I am inadvertently capturing those.

Example of text: Ref Text Word Z12345

I want to capture Z12345 only, which I know occurs after Ref always. However, I am capturing "Text" instead, using the text example above.

(?<=Ref).(\w)*

I've tried (?<=Ref).(\w)* and (?<=Ref).(\w(^aA-zZ))*

Upvotes: 0

Views: 80

Answers (1)

lemon
lemon

Reputation: 15482

You can't use a Positive Lookbehind, because it can't accept variable-length characters. Though one thing that may help you is matching without lookaround, enclose your actual match in a group and extract content of that group after pattern-match.

\bRef\b[\w\s]*?\b([a-zA-Z]\d+)\b

Your match, composed of a letter and digits, is contained in Group 1.

Check the demo here.

Note: Credits to @Thefourthbird for this regex refining.

Upvotes: 1

Related Questions