正则表达式匹配字符串中的偶然非单词

时间:2017-07-17 11:48:37

标签: regex

如何创建一个匹配字符串中所有偶然非单词“[a]。[b]”的正则表达式?我不关心空格或换行或任何我没有听说过的隐形字符,只要它只匹配偶然字符串。其他任何东西都是无效的。

[a].[b] // valid for "[a].[b]"
 [a].[b] // valid for "[a].[b]"
[a].[b]  // valid for "[a].[b]"
\n[a].[b] // valid for "[a].[b]"

[a].[b]$[c] // invalid because of "$" (or any other character) and everything after
[c]$[a].[b] // invalid because of "$" (or any other character) and everything before
[c].[a].[b] // invalid because of "[c]."

我遇到的问题是如果我尝试

[\ \n\r]

它匹配“[a]。[b]”之前的空格,这不是我想要的,我想要忽略空格,因为除了“[a]。[b]”之外我不想替换任何东西。但当然只有当它是一个偶然的字符串时,“someanythingbutspaceandnewline [a]。[b]”我不想替换。

谢谢。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望[a].[b]字符串包含可能的前导尾随空格。如果是您的情况,我建议\A\s*\[a\]\.\[b\]\s*\Z模式,例如( C#代码)

  string pattern = @"\A\s*\[a\]\.\[b\]\s*\Z";

  string source = "\n[a].[b] \t  ";

  if (Regex.IsMatch(source, pattern))
    Console.Write("Match");
  else 
    Console.Write("Not Match");

模式:

 \A           - beginning of the text 
 \s*          - zero or more leading whitespaces
 \[a\]\.\[b\] - string to find (please, notice escapements)
 \s*          - zero or more trailing whitespaces
 \Z           - end of the text 

编辑:据我所知,比赛的核心是一个常数 - [a].[b],所以我怀疑你是否真的想要比赛的文字这是"[a].[b]"。如果你这样做 您可以尝试展望未来了解构建( C#代码):

 string pattern = @"(?<=\A\s*)\[a\]\.\[b\](?=\s*\Z)";

 string source = "\n[a].[b] \t  ";  

 var match = Regex.Match(source, pattern);

 if (match.Success)
   Console.Write($"Matched: '{match.Value}'");

现在

 (?<=\A\s*) - zero or more leading spaces should be matched but not included into the match
 (?=\s*\Z) - zero or more trailing spaces should be matched but not included into the match

编辑2 :如果您将多个 [a].[b]用空格分隔(请参阅下面的评论)

  string pattern = @"(?<=\A|\s+)\[a\]\.\[b\](?=\s+|\Z)";

  string source = "[a].[b]  [a].[b][a].[b] [a].[b] \t ";

  string result = string.Join(", ", Regex
    .Matches(source, pattern)
    .OfType<Match>()
    .Select(match => match.Value));

  Console.Write(join);

结果(2场比赛):

  [a].[b], [a].[b]