假设我有一个包含允许的符号和单词的列表,如下所示:
+ - TEXT \s
有效字符串是不包含其他符号或单词的字符串。
例如,以下是有效的字符串:
TEXT + TEXT
TEXT - TEXT
以下不是:
NUMBER + TEXT
TEXT / TEXT
我需要一些帮助来构建可用于应用此类验证的正则表达式。我的问题是我无法将符号与正则表达式中的单词组合起来。
例如,当验证符号时,上面的代码工作正常:
(?n)[^\s\+-] # it is matching everything that is not a "space", "+" or "-"
但是如果我尝试添加一个词,表达式匹配它的字符,而不是词本身:
(?n)[^\s\+-\bTEXT\b]
我尝试了不同的正则表达式(用|、() 分隔参数)但失败了。
谁能告诉谁来解决这个问题?
请您参考如下方法:
您可以依赖Replace。示例代码:
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 == "");
