加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式匹配字符串的第一次出现

发布时间:2020-12-14 06:34:42 所属栏目:百科 来源:网络整理
导读:我有这个字符串: City – This is some text. This is some more – and continues here. 我想在第一个’ – ‘分割字符串以找到’city'(只是一个示例字,也可以是其他单词)。加上“ – ”后面的其余文本。 我构造了这个表达式: (^[DWS]*)( - )([DWS
我有这个字符串:

City – This is some text. This is some more – and continues here.

我想在第一个’ – ‘分割字符串以找到’city'(只是一个示例字,也可以是其他单词)。加上“ – ”后面的其余文本。

我构造了这个表达式:

(^[DWS]*)( - )([DWS]*)

但是最后发现的是’ – ‘而不是第一个。

第一次如何停止?

最简单的解决方案是明确禁止破折号成为第一组的一部分:
^([^-]*) - (.*)

说明:

^        # Start of string
([^-]*)  # Match any number of characters except dashes
 -     # Match a dash (surrounded by spaces)
(.*)     # Match anything that follows

但是,如果您的字符串可能包含第一组中的破折号(只是不被空格包围),则会失败。如果是这样,那么你可以使用懒惰量词:

^(.*?) - (.*)

说明:

^        # Start of string
(.*?)    # Match any number of characters,as few as possible
 -     # Match a dash (surrounded by spaces)
(.*)     # Match anything that follows

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读