Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find regex pattern match string have multiple condition?

Tags:

c#

regex

I have some strings formatted as follows:

1=case1,case2,..caseN;2=case1,..,caseN;3=case1, ..,caseN

Note: comma ";" is used to separate cases and case1, case2 are anything like strings, number doesn't matter their type.

I want to find regex pattern to match string

1=home,house;2=abc;3=2019,2021

however, it will not match the following:

1=home,;2=abc;3=2019,2021 (Excess comma mark at case 1)
1=;2=abc,2012;3=          (must 1=..; not 1=;)
1=home,age;2              (must 2=.. not 2)
2=home;;3=sea             (must ;3 not ;;3)
4=flower;k3=sea           (must 3= , not k3)

I tried with the pattern: (\d+={1}[^;]+;). However, it will match if the backstring is not. Please show me the way.

Many thanks!


1 Answers

Maybe this pattern helps you out:

^\b(?:(?:^|;)\d+=[^,;]+(?:,[^,;]+)*)+$

See the Online Demo


  • ^ - Start string ancor.
  • \b - Word-boundary.
  • (?: - Opening 1st non-capture group.
    • (?:- Opening 2nd non-capture group.
      • ^|; - Alternation between start string ancor or semi-colon.
    • ) - Closing 2nd non-capture group.
    • \d+= - One or more digits followed by a =.
    • [^,;]+ - Negated character class, any character other than comma or semicolon one or more times.
    • (?: - Opening 3rd non-capture group.
      • , - A comma.
      • [^,;]+ - Negated character class, any character other than comma or semicolon one or more times.
      • )* - Close 3rd non-capture group and make it match zero or more times.
  • )+ - Close 1st non-capture group and make sure it's matches one or more times.
  • $ - End string ancor.

enter image description here

Note: I went with a negated character class since you mentioned "case1, case2 are anything like strings, number doesn't matter their type", therefor I read there can be spaces, special characters or any kind other than comma and semicolon.

like image 50
JvdV Avatar answered Jun 14 '26 01:06

JvdV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!