假设我有一个包含允许符号和单词的列表,如下所示:
+ - TEXT \s
和valid
字符串是不包含其他符号或单词的字符串。
例如,以下是valid
字符串:
TEXT + TEXT
TEXT - TEXT
以下不是:
NUMBER + TEXT
TEXT / TEXT
我需要一些帮助来构建一个可用于应用此类验证的正则表达式。我的问题是我无法将符号与正则表达式中的单词组合在一起。
例如,当验证符号时,上述工作正常:
(?n)[^\s\+-] # it is matching everything that is not a "space", "+" or "-"
但如果我尝试添加一个单词,表达式会匹配其字符,而不是单词本身:
(?n)[^\s\+-\bTEXT\b]
我尝试了不同的正则表达式(将参数与|
,()
分开)但失败了。
谁能告诉谁解决这个问题?
答案 0 :(得分:2)
您可以依靠string input = "TEXT+TEXT";
List<string> allAllowed = new List<string>() { "+", "-", "TEXT", @"\s" };
//In case of having allowed words sharing common parts (e.g., TEXT & SUBTEXT),
//you would have to order the list by word-length to avoid problems
//allAllowed = allAllowed.OrderByDescending(x => x.Length).ToList();
string outString = input;
foreach (string allowed in allAllowed)
{
outString = outString.Replace(allowed, "").Trim();
//As suggested by Erresen via comments I am including Trim()
//because in the provided samples the blank spaces are not invalid characters.
}
bool inputIsValid = (outString == "");
。示例代码:
JQuery
答案 1 :(得分:1)
答案 2 :(得分:1)
我建议使用"(?:" + string.Join("|", list) + ")"
创建一个正则表达式模式来检查传入的字符串:
示例正则表达式如下所示:
^(?:\+|-|TEXT|\s)+$
请参阅regex demo
和C#代码:
var keys = new List<string>() { @"\+", "-", "TEXT", @"\s" };
var pattern = string.Format("(?:{0})", string.Join("|", keys));
Regex rx = null;
try
{
rx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
var text = "TEXT+TEXT";
if (rx.IsMatch(text))
Console.WriteLine(string.Format("\"{0}\" is valid.", text));
else
Console.WriteLine(string.Format("\"{0}\" is invalid.", text));
}
catch (ArgumentException ae)
{
Console.WriteLine(string.Format("Error parsing {0}: {1}", pattern, ae.Message));
}
请注意,您必须确保密钥是有效的正则表达式子模式。如果没有,则需要使用Regex.Escape
来转义特殊的正则表达式元字符。