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

后端 未结 5 1692
盖世英雄少女心
盖世英雄少女心 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:42

    How about the simpler

    str.match(/[^%]*/i)[0]
    

    Which means, match zero-or-more character, which is not a %.


    Edit: If need to parse until , then you could parse a sequence pf characters, followed by , then then discard the , which means you should use positive look-ahead instead of negative.

    str.match(/.*?(?=<\/a>|$)/i)[0]
    

    This means: match zero-or-more character lazily, until reaching a or end of string.

    Note that *? is a single operator, (.*)? is not the same as .*?.

    (And don't parse HTML with a single regex, as usual.)

提交回复
热议问题