啊 突然想起来 我之前用的是“\[”这个不能代表[ 要用“\\[”或者@“\[”代表[ ~~~~我出错在这儿了 但是为什么[[]能代表[??在这里面就不需要转义另外问: using System; using System.Text.RegularExpressions;public class Example { public static void Demo(System.Windows.Controls.TextBlock outputBlock) { string pattern = "--(.+?)--"; string replacement = "($1)"; string input = "He said--decisively--that the time--whatever time it was--had come."; foreach (Match match in Regex.Matches(input, pattern)) { string result = match.Result(replacement); outputBlock.Text += result + "\n"; } } } // The example displays the following output: // (decisively) // (whatever time it was)这是msdn的Match.Result方法中的只是觉得以后会碰到这种问题:如果想结果是 (decisively) (that the time) (whatever time it was) 怎么办??
啊 突然想起来 我之前用的是“\[”这个不能代表[ 要用“\\[”或者@“\[”代表[ ~~~~我出错在这儿了
但是为什么[[]能代表[??在这里面就不需要转义另外问:
using System;
using System.Text.RegularExpressions;public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
string pattern = "--(.+?)--";
string replacement = "($1)";
string input = "He said--decisively--that the time--whatever time it was--had come.";
foreach (Match match in Regex.Matches(input, pattern))
{
string result = match.Result(replacement);
outputBlock.Text += result + "\n";
}
}
}
// The example displays the following output:
// (decisively)
// (whatever time it was)这是msdn的Match.Result方法中的只是觉得以后会碰到这种问题:如果想结果是
(decisively)
(that the time)
(whatever time it was)
怎么办??
[] 本为内集或, [[] []] 并无歧义,当然可用。
[[]这种不构成歧义的,在.NET中是支持的,但在其它语言中不一定支持,所以最好不要这样用,直接用\[转义,或者多个字符取或时,还是显式的加下转义的好,比如[\s\[]至于2楼的问题string pattern = "(?<=--)(.+?)(?=--)";
当然,这样就没必要用捕获组了,只不过去掉捕获组后,要用$0,而不是$1了