【发布时间】:2012-10-03 12:19:16
【问题描述】:
我正在学习正则表达式,但仍然很难学习。
所以我的问题是这样的,我给了一组关键字:
快速的棕色狐狸
我必须在一堆句子中找到:
The Brown SexyFox 在后院跳得真快……
如果与这些单词有任何匹配(不区分大小写):
The, the, brown, Brown, fox, Fox, quick, Quick
那我可以说返回值为true
如何在正则表达式中做到这一点?我正在考虑拆分单词并放入数组并使用循环并使用.Contains(...) 找到它们,但我知道这并不理想。
其实我还有一个顾虑。但我害怕将它作为一个新问题发布。
所以我的第二个问题是,正则表达式如何读取模式?什么是优先级和最低优先级?
无论如何,请帮助我解决我的问题。
编辑
抱歉,回复晚了,但@PatrikW 的解决方案似乎不起作用。
我有静态类:
public static bool ValidateRegex(string value, string regex)
{
value += ""; // Fail safe for null
Regex obj = new Regex(regex, RegexOptions.IgnoreCase);
if (value.Trim() == "")
return false;
else
{
return obj.IsMatch(value);
}
}
构造正则表达式模式:
keyword = "maria";
string regexPattern = "(?<=\b)(";
string Or = string.Empty;
foreach (string item in keyword.Split(new char[] { ' ', ',', '.' }, StringSplitOptions.RemoveEmptyEntries).ToList())
{
regexPattern += Or + "(" + item + ")";
Or = "|";
}
regexPattern += ")(?=\b)";
数据信息:
List<Friend> useritems = null;
useritems = ((List<Friend>)SessonHandler.Data.FriendList).Where(i =>
Utility.ValidateRegex(i.LastName, regexPattern) ||
Utility.ValidateRegex(i.FirstName, regexPattern) ||
Utility.ValidateRegex(i.MiddleName, regexPattern)).ToList();
//regexPattern = "(?<=\b)((maria))(?=\b)"
//LastName = "MARIA CALIBRI"
//FirstName = "ALICE"
//MiddleName = null
可能是我的代码有问题。请帮忙。
编辑 2
我忘记了@ 符号。这现在必须工作:
string regexPattern = @"(?<=\b)(";
.
.
.
regexPattern += @")(?=\b)";
下面的答案是正确的。
【问题讨论】:
-
你试过什么?您是否开始使用正则表达式模式?你必须使用正则表达式吗?正则表达式从左到右读取。您可以根据需要将字符设置为可选或必需。