我有这个字符串:
1 = 0 AND 2 = 3
我正在使用这个正则表达式:
\s*(?<SearchCondition>.+?)\s*(AND|OR|$)
我想在(http://regexhero.net/tester/)中显示以下内容,但由于某种原因它没有:
1: AND
SearchCondition: 1 = 0
1:
SearchCondition: 2 = 3
这是我的代码:
Dim whereElem As String = "1 = 0 AND 2 = 3"
Dim regex As New Regex("\s*(?<SearchCondition>.+?)\s*(AND|OR|$)", RegexOptions.IgnoreCase)
m = regex.Match(whereElem)
If m.Success Then
Console.WriteLine(m.Groups("SearchCondition").Captures.Count)
期望的输出:2
我在这里做错了什么但是没有看到它。我出错的任何提示?
答案 0 :(得分:2)
您的正则表达式只匹配单个表达式,后跟AND
,OR
或字符串的结尾:
\s* # whitespace
(?<SearchCondition>.+?) # match and capture before the whitespace
\s* # more whitespace
(AND|OR|$) # either AND, OR, or end of line
由于您的输入为1 = 0 AND 2 = 3
,因此调用Regex.Match
将在第一个AND
之后停止。
您可能希望使用Regex.Matches
来查找所有匹配项:
var matches = regex.Matches(whereElem);
foreach (Match m in matches)
Console.WriteLine(m.Groups["SearchCondition"]);
希望你不介意用C#解答答案。
答案 1 :(得分:1)
当String
类提供一种简单的方法时,为什么需要一个正则表达式来处理这个简单的事情。
如果事情不是太复杂,不建议使用正则表达式,因为它们具有处理开销。
以下是针对您的单线解决方案:
Dim searchConditions() As String = whereElem.Split(New String() {" AND ", " OR "}, StringSplitOptions.None)