我有一个像这样的字符串 -"Bangalore,India=Karnataka"
。我只想从这个字符串中提取子字符串"Bangalore"
。在这种情况下,正则表达式可以是 -(.+),.*=.*
。但问题是,字符串有时可能只是"Bangalore"
。那么在这种情况下,上面的正则表达式将不起作用。获取子字符串的正则表达式是什么"Bangalore"
无论字符串是什么?
试试这个:
^(.+?)(?:,.*?)?=.*$
解释:
^ # 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:
我以为OP必须匹配Bangalore,India=Karnataka
or Bangalore=Karnataka
但据我了解Bangalore,India=Karnataka
or Bangalore
所以正则表达式更简单:
^([^,]+)
这将在字符串的开头匹配一个或多个非逗号字符并将它们捕获到组 1 中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)