Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 正则表达式以匹配字符串的第一个匹配项_Regex - Fatal编程技术网

Regex 正则表达式以匹配字符串的第一个匹配项

Regex 正则表达式以匹配字符串的第一个匹配项,regex,Regex,我有这个字符串: 城市-这是一些文本。这是更多的,并在这里继续 我想在第一个“-”处拆分字符串以查找“city”(只是一个示例单词,也可以是其他单词)。加上以查找'-'之后的其余文本 我构建了这个表达式: (^[\D\W\S]*)( - )([\D\W\S]*) 但这会找到最后一个出现的“-”,而不是第一个 如何在第一次出现时停止?最简单的解决方案是明确禁止破折号成为第一组的一部分: ^([^-]*) - (.*) 说明: ^ # Start of string ([^-]*)

我有这个字符串:

城市-这是一些文本。这是更多的,并在这里继续

我想在第一个“-”处拆分字符串以查找“city”(只是一个示例单词,也可以是其他单词)。加上以查找'-'之后的其余文本

我构建了这个表达式:

(^[\D\W\S]*)( - )([\D\W\S]*)
但这会找到最后一个出现的“-”,而不是第一个


如何在第一次出现时停止?

最简单的解决方案是明确禁止破折号成为第一组的一部分:

^([^-]*) - (.*)
说明:

^        # 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
但是,如果字符串在第一个组中包含破折号(只是没有被空格包围),则此操作将失败。如果是这种情况,那么您可以使用惰性量词:

^(.*?) - (.*)
说明:

^        # 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

大多数语言都有按特定字符分割字符串的函数,甚至允许您限制分割的数量。你应该使用这样一个函数。如果您让我们知道您使用的是哪种语言,我们可以为您提供更多帮助。这取决于正则表达式引擎。你在用什么?来吧伙计们,为什么要否决这个?这是一个公平的问题,他做了一些研究工作,并展示了他所做的尝试。这比我们从大多数新来者那里得到的要多得多。所以,从我这里,用户1391459,欢迎来到StackOverflow,坚持住!(选择一个更好的用户名也是一个好主意:))顺便问一下,你是如何想出
[\D\W\s]
的?它的意思是“不是数字或不是字母数字的字符(已经包括“不是数字”)或不是空白字符。因此,它匹配任何字符,在正则表达式中,这就是点(
:任何字符(新行除外))的含义。除非您使用JavaScript,在这种情况下,您可能需要
[\s\s]
如果您没有允许指定单线模式的选项,则点确实匹配任何字符。我需要表达式来匹配Drupal Feeds xpath解析器中的特定文本。点是不够的,因为它还应匹配换行符。由于我的测试,我错误地将其遗漏在这里。[\S\S].*不起作用。我实际使用[\D\W\S\n]现在。我为php找到了替代方案/(.*)/sU,但在xpath解析器中不起作用。非常好!还感谢您的快速响应。因为文本也有换行符,而且末尾有一个数字应该省略,所以这是有效的:^(.*)-([\D\W\S\n]*)\D{10}很好,很高兴听到。但是你最好使用
[\S\S]*
而不是
[\d\W\S\n]*