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

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

    I just wrote it exactly how you said it:

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

    This will match any string without a '%' or the first part of a string that contains a %. You have to get the result from the 1st or 2nd group.

    EDIT: This is exactly what you want below

    str.match(/(?:^[^%]*$)|^(?:[^%]*)(?=%)/)
    
    • The ?: removes all grouping
    • The ?= is a lookahead to see if the string contains %
    • and [^%] matches any character that is not a %

    so the regex reads match any string that doesnt contain %, OR (otherwise match) all of the characters before the first %

提交回复
热议问题