我有这个字符串:
城市 - 这是一些文字.这是更多 - 并继续在这里.
我想在第一个' - '分割字符串以找到'city'(只是一个示例单词,它也可以是其他单词).另外,在" - "之后找到文本的其余部分.
我构造了这个表达式:
(^[\D\W\S]*)( - )([\D\W\S]*)
Run Code Online (Sandbox Code Playgroud)
但是这会发现最后一次出现' - '而不是第一次出现.
我怎么能在第一次出现时停下来?
Tim*_*ker 39
最简单的解决方案是明确禁止破折号成为第一组的一部分:
^([^-]*) - (.*)
Run Code Online (Sandbox Code Playgroud)
说明:
^ # Start of string
([^-]*) # Match any number of characters except dashes
\ - \ # Match a dash (surrounded by spaces)
(.*) # Match anything that follows
Run Code Online (Sandbox Code Playgroud)
但是,如果你的字符串,这将失败,可能 包含在第一组中的破折号(只是没有用空格包围).如果是这种情况,那么你可以使用惰性量词:
^(.*?) - (.*)
Run Code Online (Sandbox Code Playgroud)
说明:
^ # Start of string
(.*?) # Match any number of characters, as few as possible
\ - \ # Match a dash (surrounded by spaces)
(.*) # Match anything that follows
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45065 次 |
| 最近记录: |