I'm looking for a regex pattern with the following particulars
%
, @
, /
, -
etc2342 34534 2342
. however 345345 / 435
or 236 545
is fineMatches
"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"
Just to be more specific. The following should not match
"1 3 5"
"34 a a"
"34b s"
"56/v"
"234 / a"
"234a/a"
"34b 456s"
"34b/456s"
"34b / 456s"
My current attempt is ^\\d+[\\s]?[az\\W]?[\\s]?[\\W]?[\\s]?\\d+?[az]?$
Although I'll most likely need more than one pattern (for the letters either side of the symbol), my main problem is trying to get the ?
to work correctly, ie with the current pattern id expect to get more positives
Update
The current regex produces the following results.
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
Ignoring the false positives, which I can fix by creating 2 patterns, I'm stuck on why the current regex is not matching on those pointed out.
Guessing from your description, I suggest the following pattern:
^\d+\s?(?:\W\s?\d+(?:\s?[a-z])?|(?:\d+\s?)?[a-z]?|[a-z]\s?\W\s?\d+)$
Sample Code:
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));
}
}
}
You may try this too.
(?im)^(?!(?:\d+\s){2}\d+\s*$)[^a-z\n]*(?:(?:\d\s?)[a-z])?[^a-z\n]*$
Demo in .NET regex tester ,,, please click tabs, [table]
and [context]
for more infomation of matching.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.