Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding a regex

Tags:

java

regex

I am looking to decode a regular expression. Is there a way to check what the below regex means:

^(PC([Y\\d])|GC([Y\\d])|Y|\\d)\\d{4,5}$
like image 705
user179516 Avatar asked Sep 26 '26 15:09

user179516


2 Answers

You could use the Regular Expression Analyzer at http://www.myezapp.com/apps/dev/regexp/show.ws or http://www.debuggex.com/


^ = start of string
() = capturing groups
[] = character classes
\d = digit in 0-9
\\ = literal backslash
| = OR
{} = count of leading item
$ = end of string
like image 91
Anirudh Ramanathan Avatar answered Sep 28 '26 04:09

Anirudh Ramanathan


Here is a break down of what is happening.

Regex: ^(PC([Y\\d])|GC([Y\\d])|Y|\\d)\\d{4,5}$

 1. ^        -  Beginning of line  
 2. (        -  Beginning of a capture group
 3. PC       -  Finds `PC` exactly  
 4. ([Y\\d]) -  Creates a capture group for a Y or a single digit (0-9)
 5. |        -  This is an OR statement
 6. GC       -  Finds `GC` exactly
 7. ([Y\\d]) -  Same as 4
 8. |        -  This is an OR statement
 9. Y        -  Finds `Y` exactly
10. |        -  This is an OR statement
11. \\d      -  This looks for a single digit (0-9)
12. )        -  End of capture group.  Lines 3-11 will be in this capture group
13. \\d{4,5} -  This will look any digit exactly 4 or 5 times
14. $        -  End of line

There are 3 capture groups in this:

1. (PC([Y\\d])|GC([Y\\d])|Y|\\d)
2. ([Y\\d])  (The first one)
3. ([Y\\d])  (The second one)

Here is a list of valid matches (any number would be found, I just used 123456 to show how many number places there can be):

  • PCY1234
  • PCY12345
  • PCY1234
  • PCY12345
  • PC12345
  • PC123456
  • GC12345
  • GC123456
  • GCY1234
  • GCY12345
  • Y1234
  • Y12345
  • 12345
  • 123456

Here is a link to RegExr with explanations of the capture groups for each match.

Also, the reason for the double \ in \\d is to escape the \ for Java. Not all languages need this, and from what I understand, there are some that need 3. If you notice in the RegExr above, I removed them so RegExr would correctly parse the Regex.

like image 30
Nick Avatar answered Sep 28 '26 04:09

Nick



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!