Reputation: 717
I need to use regular expressions to parse a string.
Most times, the string can be parsed using the expression
^([a-zA-Z\-\,0-9\(\)\#\/ \.]{1,21})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})
Sometimes, the string needs to include an additional 4 characters so the expression would be
^([a-zA-Z\-\,0-9\(\)\#\/ \.]{1,25})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})
By themselves either expression would work on their respective strings. The first will also be technically valid on a string intended for the second expression, however the .{0,9} section of the expression would be off by 4 characters.
A quick explanation of the expression: Subset 1: 1 - 21 (or 25 characters) any characters a-z any characters A-Z the dash, the comma any digits 0-9 the open and close parenthesis, the hash tag, forward slash, space and period. Subsets 2-7 Any characters (up to 9 total)
I was hoping for something like the expression below
^([a-zA-Z\-\,0-9\(\)\#\/ \.]{1,21|25})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})
OR
^([a-zA-Z\-\,0-9\(\)\#\/ \.]{1,21}|{1,25})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})
I tried these and they didn't work. Anyone else got any ideas?
Upvotes: 1
Views: 145
Reputation: 149020
It's rather verbose, but I think you'd have to do this:
^([a-zA-Z\-\,0-9\(\)\#\/ \.]{1,21}|[a-zA-Z\-\,0-9\(\)\#\/ \.]{25})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})(.{0,9})
The first capture group must be either 1-21 characters, or 25 characters long.
If you're willing to change how your groups are captured (and if your regex engine supports it), you might also be able to do this:
^([a-zA-Z\-\,0-9\(\)\#\/ \.]{1,21}|[a-zA-Z\-\,0-9\(\)\#\/ \.]{25})(.{0,9}){6}
Upvotes: 1