3

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!

6
  • 1
    You second line is not valid Commented Aug 17, 2017 at 13:44
  • 5
    The 'T' in 4FOT isn't Hex either. :-) Commented Aug 17, 2017 at 13:45
  • @SamvelPetrosov, fixed thanks Commented Aug 17, 2017 at 13:47
  • Is 3F00/FA41 (without spaces) valid? Commented Aug 17, 2017 at 13:55
  • Do you only want to validate if a line obeys the regex pattern, or do you also want to extract the matched 4-character words? Commented Aug 17, 2017 at 13:56

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

This allows more than 4 blocks, which would be invalid
@Mr. Toast: if we want up to 4 blocks; {,3} should be used instead of *
3

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 /.

Comments

1

I think this might work, if the input is given line by line:

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

2 Comments

Does not work if the blocks contain different characters: FFFF / FFFF = valid; 2222 / 1111 = invalid
Remove the back reference, then it should work. Sorry forgot to remove that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.