java regex : getting a substring from a string which can vary

后端 未结 5 1663
借酒劲吻你
借酒劲吻你 2021-01-22 19:53

I have a String like - \"Bangalore,India=Karnataka\". From this String I would like to extract only the substring \"Bangalore\". In this case the regex

5条回答
  •  忘掉有多难
    2021-01-22 20:26

    Try this one:

    ^(.+?)(?:,.*?)?=.*$
    

    Explanation:

    ^               # Begining of the string
      (             # begining of capture group 1
        .+?         # one or more any char non-greedy
      )             # end of group 1
      (?:           # beginig of NON capture group
        ,           # a comma
        .*?         # 0 or more any char non-greedy
      )?            # end of non capture group, optional
      =             # equal sign
      .*            # 0 or more any char
    $               # end of string
    

    Updated: I thougth OP have to match Bangalore,India=Karnataka or Bangalore=Karnataka but as farr as I understand it is Bangalore,India=Karnataka or Bangalore so the regex is much more simpler :

    ^([^,]+)
    

    This will match, at the begining of the string, one or more non-comma character and capture them in group 1.

提交回复
热议问题