Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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
C# 如何在字符串中查找所有匹配项_C#_Regex - Fatal编程技术网

C# 如何在字符串中查找所有匹配项

C# 如何在字符串中查找所有匹配项,c#,regex,C#,Regex,假设我有以下字符串: xx#a#11#yyy#bb#2#z 我正在尝试检索所有出现的###某物#某物#### (在我的字符串中,我希望有两个匹配项:##a#11##和##bb#2##) 我尝试使用 Regex.Matches(MyString, ".*(##.*#.*##).*") 但它检索一个匹配项,即整行 如何从该字符串中获取所有匹配项?谢谢。因为在图案的开头和结尾都有*,所以只能得到整行匹配。此外,模式中介于#之间的*太贪婪了,当在一行中遇到时,会将所有预期的匹配项抓取为一个匹配项 你可

假设我有以下字符串:

xx#a#11#yyy#bb#2#z

我正在尝试检索所有出现的
###某物#某物####

(在我的字符串中,我希望有两个匹配项:
##a#11##
##bb#2##

我尝试使用

Regex.Matches(MyString, ".*(##.*#.*##).*")
但它检索一个匹配项,即整行


如何从该字符串中获取所有匹配项?谢谢。

因为在图案的开头和结尾都有
*
,所以只能得到整行匹配。此外,模式中介于
#
之间的
*
太贪婪了,当在一行中遇到时,会将所有预期的匹配项抓取为一个匹配项

你可以用

var results = Regex.Matches(MyString, "##[^#]*#[^#]*##")
    .Cast<Match>()
    .Select(m => m.Value)
    .ToList();
Regex.Matches(MyString,“(##[^#]+#[^#]+#+)”


描述

1st Capturing Group (##[^#]+#[^#]+##)
    ## matches the characters ## literally (case sensitive)
    Match a single character not present in the list below [^#]+
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    # matches the character # literally (case sensitive)
    # matches the character # literally (case sensitive)
    Match a single character not present in the list below [^#]+
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    # matches the character # literally (case sensitive)
    ## matches the characters ## literally (case sensitive)


与*的问题是它将匹配
@abc123:这取决于需求,然后可以将
*
替换为
+
。我添加了更多的调整选项作为注释。谢谢:)根据您的帮助,我还设法在不使用封闭的###的情况下获得匹配项(即获得a#1而不是##a###)。我使用了这种模式:[^##][^#]*.[^#]*[^#].[^##].[^##].[^##].[^##].[^##].]但接下来您将使用一个捕获组,让我演示一下。
(##[^#]+#[^#]+##)
1st Capturing Group (##[^#]+#[^#]+##)
    ## matches the characters ## literally (case sensitive)
    Match a single character not present in the list below [^#]+
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    # matches the character # literally (case sensitive)
    # matches the character # literally (case sensitive)
    Match a single character not present in the list below [^#]+
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    # matches the character # literally (case sensitive)
    ## matches the characters ## literally (case sensitive)