我正在寻找具有以下细节的正则表达式模式
%
,@
,/
,-
等2342 34534 2342
。但是345345 / 435
或236 545
没问题匹配
"1"
"12"
"12 34"
"12 a 34"
"1a"
"54b"
"32 c"
"43-23"
"45 c/34"
"45/34 d"
"67 / 345"
"23a / 56"
"12 / 56B"
更具体一点。
符合以下条件"1 3 5"
"34 a a"
"34b s"
"56/v"
"234 / a"
"234a/a"
"34b 456s"
"34b/456s"
"34b / 456s"
我目前的尝试是^\d+[\s]?[a-z\W]?[\s]?[\W]?[\s]?\d+?[a-z]?$
虽然生病最有可能需要多个模式(对于符号两边的字母),我的主要问题是试图使?
正常工作,即当前模式id期望得到更多积极的
更新
当前正则表达式产生以下结果。
Good list
-------------
False - 1 <= this should match
True - 12 34
True - 12 a 34
False - 1a <= this should match
True - 54b
False - 32 c <= this should match
True - 43-23
True - 45c/34
True - 45/34d
True - 67 / 345
True - 23a / 56
True - 12 / 56b
Bad list
-------------
False - 1 3 5
False - 34 a a
False - 34b s
False - 234a/a
True - 34b 456s <= these are false positives only because they have 2 letters
True - 34b/456s
True - 34b / 456s
忽略误报,我可以通过创建2个模式来解决这个问题,但我仍然坚持为什么当前的正则表达式与那些指出的不匹配
答案 0 :(得分:1)
根据您的描述猜测,我建议使用以下模式:
^\d+\s?(?:\W\s?\d+(?:\s?[a-z])?|(?:\d+\s?)?[a-z]?|[a-z]\s?\W\s?\d+)$
示例代码:
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var goodList = new List<string>{"1", "12", "12 34","12 a 34", "1a", "54b", "32 c", "43-23", "45c/34", "45/34d", "67 / 345", "23a / 56", "12 / 56b"};
var badList = new List<string>{"1 3 5", "34 a a", "34b s", "234a/a", "34b 456s", "34b/456s", "34b / 456s"};
var pattern = @"^\d+\s?(?:\W\s?\d+(?:\s?[a-z])?|(?:\d+\s?)?[a-z]?|[a-z]\s?\W\s?\d+)$";
var regex = new Regex(pattern);
Console.WriteLine("Good list");
Console.WriteLine("-------------");
foreach (var item in goodList)
{
Console.WriteLine(string.Format("{0} - {1}", regex.IsMatch(item), item));
}
Console.WriteLine();
Console.WriteLine("Bad list");
Console.WriteLine("-------------");
foreach (var item in badList)
{
Console.WriteLine(string.Format("{0} - {1}", regex.IsMatch(item), item));
}
}
}
答案 1 :(得分:1)
您也可以尝试一下。
(?im)^(?!(?:\d+\s){2}\d+\s*$)[^a-z\n]*(?:(?:\d\s?)[a-z])?[^a-z\n]*$
Demo in .NET regex tester ,,,请点击标签[table]
和[context]
了解更多匹配信息。