Regex match until first instance of certain character

前端 未结 1 1216
醉梦人生
醉梦人生 2020-12-31 04:50

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 do

相关标签:
1条回答
  • 2020-12-31 05:13

    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 (^).

    0 讨论(0)
提交回复
热议问题