Javascript regular expression: match anything up until something (if there it exists)

后端 未结 5 1697
盖世英雄少女心
盖世英雄少女心 2021-02-05 06:18

Hi I am new to regular expression and this may be a very easy question (hopefully).

I am trying to use one solution for 3 kind of string

  • \"45%\", expected
5条回答
  •  不思量自难忘°
    2021-02-05 06:29

    I think this is what you're looking for:

    /(?:(?!%).)*/
    

    The . matches any character, but only after the negative lookahead, (?!%), confirms that the character is not %. Note that when the sentinel is a single character like %, you can use a negated character class instead, for example:

    /[^%]*/
    

    But for a multi-character sentinel like , you have to use the lookahead approach:

    /(?:(?!).)*/i
    

    This is actually saying "Match zero or more characters one at a time, but if the next character turns out to be the beginning of the sequence or , stop without consuming it".

提交回复
热议问题