Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match until first instance of certain character

Tags:

regex

I am trying to match a url up until a special character however the regex I am using is match the last instance when I need it to stop after the first instance. What am I doing wrong?!

.+?(?=\")

To match everything until first "

However my result is below:

enter image description here

like image 755
NeverPhased Avatar asked Dec 02 '16 23:12

NeverPhased


People also ask

How do I match a specific character in regex?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

How do you match something before a word in regex?

A regular expression to match everything before a specific character makes use of a wildcard character and a capture group to store the matched value. Another method involves using a negated character class combined with an anchor.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you match a specific sentence in regex?

Example is: string pattern = @"(Band) (? <Band>[A-Za-z ]+) (? <City>@[A-Za-z ]+) (?


1 Answers

You added the " into the consuming part of the pattern, remove it.

^.+?(?=\")

Or, if you need to match any chars including line breaks, use either

(?s)^.+?(?=\")
^[\w\W]+?(?=\")

See demo. Here, ^ matches start of string, .+? matches any 1+ chars, as few as possible, up to the first " excluding it from the match because the "` is a part of the lookahead (a zero-width assertion).

In the two other regexps, (?s) makes the dot match across lines, and [\w\W] is a work-around construct that matches any char if the (s) (or its /s form) is not supported.

Best is to use a negated character class:

^[^"]+

See another demo. Here, ^[^"]+ matches 1+ chars other than " (see [^"]+) from the start of a string (^).

like image 126
Wiktor Stribiżew Avatar answered Sep 21 '22 14:09

Wiktor Stribiżew