I’m looking for a regular expression to match an alphanumeric string. If the string is 32 characters long, match characters 17 to 28. If the string is 34 characters long, match the last 12 characters.
RegEx Match Conditions http://s12.postimage.org/ghathiz2l/Screen_shot_2012_08_09_at_11_52_22_PM.png
I have two separate expressions to get matches for the two different conditions.
.(?<match>[0-9]{16}) and .(?<match>[0-9]{12})
In the code, I read the expressions right to left, handle the ‘if’ and truncate the last 4 characters of the match when the original string is 32 characters long but would like to be able to do this from a single RegEx.
EDIT
I would indeed prefer to do away with the RegEx in this case but I am not the original author of the app. The string-parsing conditions may change over time so it is simpler to maintain the RegEx in the config file than to make a new release in this instance. Plus, it’s what the boss wants…
Try this:
$1is the entire match for the first case (34 chars long);$2is the matched 12 chars.$3is the entire match for the second case (32 chars long);$4is the matched 12 chars.Easy!
The other, and arguably easier, way, is to look at the inbound string and assign the correct regex instance based on string length:
Or, why use the regex at all? This isn’t a problem for a regex.
Because life is too hard to make things more difficult than they are.