Reputation: 337
I'm trying to do some validation on a string.
Y0 40 98 86 A
I would like to be able to replace the 0
's which occur in the first 2 characters ie Y0
with O's.
I know how to do the replace part but am struggling to just select that first 0.
It should match all 0's within that first two characters. Ie 00
0Z
etc
To clarify, I don't mind what language I just need helping making the Regex Selector
Upvotes: 1
Views: 54
Reputation: 54303
Thanks to @Rawing for the comment:
"00 40 98 86 A".gsub(/^0|(?<=^.)0/, 'O')
# "OO 40 98 86 A"
The regex means :
Another variant by @SebastianProske:
"A0 40 98 86 A".gsub(/(?<!..)0/, 'O')
# "AO 40 98 86 A"
It means : a 0, but only when not preceded by two characters
.
Here's a test.
It might be easier to do it in two steps. Replace the first character by O
if it's a 0
, then replace the second character if it's a 0
.
Here's a ruby example with a matching group:
"Y0 40 98 86 A".sub(/^0/,'O').sub(/^(.)0/,'\1O')
# "YO 40 98 86 A"
You could also use a lookbehind:
"Y0 40 98 86 A".sub(/^0/,'O').sub(/(?<=^.)0/,'O')
=> "YO 40 98 86 A"
Upvotes: 1