Liably
Liably

Reputation: 337

Regex only searching part of a string

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

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54303

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"

Upvotes: 1

Related Questions