1

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

0

1 Answer 1

1

One-step replacement

Thanks to @Rawing for the comment:

"00 40 98 86 A".gsub(/^0|(?<=^.)0/, 'O')
# "OO 40 98 86 A"

The regex means :

  • start of the string, followed by:
    • zero, or
    • a character, followed by a zero.

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.

Two steps replacement

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

7 Comments

Yes I' m afraid It may come to that although it would be preferable to select them all in one.
Why not merge those two regexes into a single one? /^0|(?<=^.)0/
So there's no way to think about it like: ^.{2} to select the first 2 characters and then matching inside the first match wit ha simple 0?
@SebastianProske: Thanks, that's even cleaner.
The regex you provided in your example is perfect thank you.
|

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.