简体   繁体   中英

Multiple Regex Pattern with different formats

I have expression like this and I want match only digits inside the parenthesis just after from totalamount and minamount

"test test test test totalamount(32604) > 0m)"
"test test test test totalamount(32604, 13456) > 0m)"
"test test test test minamount(32604) > 0m)"
"test test test test minamount(32604, 34677, 12345) > 0m)"

So if I could have the right pattern my output should be

1- 32604
2- 32604, 13456
3- 32604
4- 32604, 34677, 12345





Regex regex = new Regex(@"(totalamount)\((\d*)(\,\d*)");
Regex regex2 = new Regex(@"(totalamount)\((\d*)(\d*)");
Regex regex3 = new Regex(@"(minamount)\((\d*)(\,\d*)");
Regex regex4 = new Regex(@"(minamount)\((\d*)(\d*)");

return regex.Match(expression).Success ? regex.Match(expression) : 
                   regex2.Match(expression).Success ? regex2.Match(expression):
                   regex3.Match(expression).Success ? regex3.Match(expression) :
                   regex4.Match(expression).Success ? regex4.Match(expression) : null;

Here is my solution but thats the worst solution I think there must be better way to match my case. Can anyone help please ?

这是我的解决方案,使用单个正则表达式模式,使用更改:

(?<=(total|min)(amount)\()\d*((\, )*\d*)*

Another solution:

List<string> ls = new List<string>()
                {
                "test test test test totalamount(32604) > 0m)",
                "test test test test totalamount(32604, 13456) > 0m)",
                "test test test test minamount(32604) > 0m)",
                "test test test test minamount(32604, 34677, 12345) > 0m)"
                };

string pattern = @"(?<=(?:total|min)amount\(|\G(?!^)[ ,]*)\d+";
var result = ls.SelectMany(s =>
            Regex.Matches(s, pattern).Cast<Match>()
                  .Select(m=>Convert.ToInt32(m.Value)))
               .ToList();

Returns ( List<int> ):

32604 
32604 
13456 
32604 
32604 
34677 
12345 

I'm not sure why the previous two solutions need look-arounds, but here is a simple one without them:

(total|min)amount\(([\d,\s]+)\)

This will match the argument list and store it in capture group $2 which is accessed via the Groups property of a Match at index 2 .

Example:

var expressions = new []
{
    "test test test test totalamount(32604) > 0m)",
    "test test test test totalamount(32604, 13456) > 0m)",
    "test test test test minamount(32604) > 0m)",
    "test test test test minamount(32604, 34677, 12345) > 0m)"
};


var numbers = new Regex(@"(total|min)amount\(([\d,\s]+)\)");

foreach (var expression in expressions)
    Console.WriteLine(numbers.Match(expression).Groups[2]);

Working example: https://dotnetfiddle.net/m3iXF5

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM