Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific regex in C# .NET

Tags:

c#

.net

regex

I need to build a regular expression which should apply for the following:

(Valid for 1 - 4 Blocks (seperated with "/") which contain exactly 4 characters that are HEX numbers)

Valid example 1: 3F00 / FA41 / FA12 / B12F
Valid example 2: 4F0T
Valid example 3: FFFF / FF21

Invalid example 1: 34BF /
Invalid example 2: 45FB2
Invalid example 3: 4B5S / BD45 BA56
Invalid example 4: FF02/B200
...

I just can't figure it out. Here's what I have for now:

1: ([0-9A-F]{4})( \/ \1){1,3}|[0-9A-F]{4}
2: [0-9A-F]{4} \/ [0-9A-F]{4} \/ [0-9A-F]{4} \/ [0-9A-F]{4}|[0-9A-F]{4} \/ [0-9A-F]{4} \/ [0-9A-F]{4}|[0-9A-F]{4} \/ [0-9A-F]{4}|[0-9A-F]{4}

Second pretty ugly and both not working!

like image 271
Mr. Toast Avatar asked Dec 11 '25 07:12

Mr. Toast


2 Answers

I suggest

 ^[0-9A-F]{4}( \/ [0-9A-F]{4}){0,3}$

pattern:

 ^                      - string start
 [0-9A-F]{4}            - 4 hex digits
 ( \/ [0-9A-F]{4}){0,3} - up to 3 more 4 digits groups
 $                      - string end
like image 70
Dmitry Bychenko Avatar answered Dec 13 '25 20:12

Dmitry Bychenko


This should do the trick:

^[\dA-F]{4}( \/ [\dA-F]{4}){0,3}$

It matches the first block (4 hex characters) and then optionally matches 0-3 subsequent blocks separated by /.

like image 25
Andrew Avatar answered Dec 13 '25 21:12

Andrew



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!