Regex lookahead with unknown number of spaces

Viewed 172

I am trying to capture a string that can contain any character but must always be followed by ';' I want to capture it and trim the white space around it. I've tried using positive lookahead but that does not seem to exclude the whitespace. Example:

this is a match   ;
this is not a match

regex:

.+(?=\s*;)

result:

"this is a match " gets captured with trailing white space behind.

expected result:

"this is a match" (without whitespace)

3 Answers

You have to make sure the first and the last characters of your match are not spaces. Thus we use the non-whitespace character match (\S) before and after the all character match (.*). As spaces might be optional, the any character match (.) must be optional, thus we use * instead of +.

\S.*\S(?=\s*;)

If the string can start with space use .*\S(?=\s*;).

Demonstration

Thanks to @CarySwoveland for improving the answer.

You can match

.*(?<!\s)(?=\s*;)

provided the regex engine supports negative lookbehinds.

Demo

Note that this returns an empty string if the string is " ;".

You can make the dot non greedy and start the match with a non whitespace character:

\S.*?(?=\s*;)

Regex demo

If the non whitespace character itself should also not be a semicolon:

[^\s;].*?(?=\s*;)
Related