How to match “anything up until this sequence of characters” in a regular expression?

后端 未结 12 2135
旧时难觅i
旧时难觅i 2020-11-22 11:51

Take this regular expression: /^[^abc]/. This will match any single character at the beginning of a string, except a, b, or c.

If you add a *

12条回答
  •  伪装坚强ぢ
    2020-11-22 12:23

    If you're looking to capture everything up to "abc":

    /^(.*?)abc/
    

    Explanation:

    ( ) capture the expression inside the parentheses for access using $1, $2, etc.

    ^ match start of line

    .* match anything, ? non-greedily (match the minimum number of characters required) - [1]

    [1] The reason why this is needed is that otherwise, in the following string:

    whatever whatever something abc something abc
    

    by default, regexes are greedy, meaning it will match as much as possible. Therefore /^.*abc/ would match "whatever whatever something abc something ". Adding the non-greedy quantifier ? makes the regex only match "whatever whatever something ".

提交回复
热议问题