Regex: matching up to the first occurrence of a character

Viewed 786628

I am looking for a pattern that matches everything until the first occurrence of a specific character, say a ";" - a semicolon.

I wrote this:

/^(.*);/

But it actually matches everything (including the semicolon) until the last occurrence of a semicolon.

14 Answers

You need

/^[^;]*/

The [^;] is a character class, it matches everything but a semicolon.

^ (start of line anchor) is added to the beginning of the regex so only the first match on each line is captured. This may or may not be required, depending on whether possible subsequent matches are desired.

To cite the perlre manpage:

You can specify a character class, by enclosing a list of characters in [] , which will match any character from the list. If the first character after the "[" is "^", the class matches any character not in the list.

This should work in most regex dialects.

Would;

/^(.*?);/

work?

The ? is a lazy operator, so the regex grabs as little as possible before matching the ;.

/^[^;]*/

The [^;] says match anything except a semicolon. The square brackets are a set matching operator, it's essentially, match any character in this set of characters, the ^ at the start makes it an inverse match, so match anything not in this set.

None of the proposed answers did work for me. (e.g. in notepad++) But

^.*?(?=\;)

did.

Try /[^;]*/

Google regex character classes for details.

This was very helpful for me as I was trying to figure out how to match all the characters in an xml tag including attributes. I was running into the "matches everything to the end" problem with:

/<simpleChoice.*>/

but was able to resolve the issue with:

/<simpleChoice[^>]*>/

after reading this post. Thanks all.

this is not a regex solution, but something simple enough for your problem description. Just split your string and get the first item from your array.

$str = "match everything until first ; blah ; blah end ";
$s = explode(";",$str,2);
print $s[0];

output

$ php test.php
match everything until first

This works for getting the content from the beginning of a line till the first word,

/^.*?([^\s]+)/gm

I faced a similar problem including all the characters until the first comma after the word entity_id. The solution that worked was this in Bigquery:

SELECT regexp_extract(line_items,r'entity_id*[^,]*') 
Related