如何查找由某个开始和结束字符分隔的字符串
问题描述:
我想基于使用正则表达式的开始和结束字符来创建一个字符串数组。如何查找由某个开始和结束字符分隔的字符串
一个例子将帮助我解释。 考虑'$'作为我的起始标识符和'|'作为我从下面的字符串结束标识符
stack $ over |流程$ stack |交换
正则表达式应该找到在上面的字符串超过和堆栈。
[编辑,包括在OP的评论代码片段...]
string testingString = "stack $over| flow $stack| exchange";
var pattern = @"(?$.*?|)"; // also tried @"\$[^|]\|"
foreach (var m in System.Text.RegularExpressions.Regex.Split(testingString, pattern)) {
Response.Write(m);
}
// output == stack $over| flow $stack| exchange
答
我会使用后视和前瞻来排除匹配的开始和结束分隔符。
string testingString = @"stack $over| flow $stack| exchange";
MatchCollection result = Regex.Matches
(testingString,
@"
(?<=\$) # This is a lookbehind, it ensure there is a $ before the string
[^|]* # Match any character that is not a |
(?=\|) # This is a lookahead,it ensures that a | is ahead the pattern
"
, RegexOptions.IgnorePatternWhitespace);
foreach (Match item in result) {
Console.WriteLine(item.ToString());
}
的RegexOptions.IgnorePatternWhitespace
是能够写出易读的正则表达式,还可以使用在正则表达式评论一个有用的选项。
+0
+1这是一个很好的答案,完全可重用! – 2014-06-05 14:42:37
答
在正则表达式$
是一个特殊字符,意思是“匹配字符串的结尾”。 对于字面$
您需要转义它,请尝试\$
。
同理|
是正则表达式中的一个特殊字符,需要转义。
尝试\$.*?\|
或\$[^|]+\|
。
了解网络中的正则表达式,例如here。
[更新] 在回答您的意见,要提取文本由$
和|
界定,它不分裂。尝试Regex.Matches
而不是Regex.Split
。
Regex t = new Regex(@"\$([^|]+)\|");
MatchCollection allMatches = t.Matches("stack $over| flow $stack| exchange");
那你应该......那样做。或者至少*尝试*做到这一点。 [你试过了什么?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-01-08 07:02:41
“什么阻止你?” – Shai 2012-01-08 07:04:03
(?$。*?|)试过类似这样的东西,但我对正则表达式知之甚少 – Shah 2012-01-08 07:05:30