MikaAK
MikaAK

Reputation: 2364

Match exact word in string ruby regex

I have this string in ruby and I'm trying to make a match for sin

"please don't share this: 234-604-142"
"please don't share this: 234-604-1421"

so far I have

\d{3}-\d{3}-\d{3}

but this will also match the second case. Adding a ^ and $ for begins and ends will cause this not to function at all.

To fix this I could do this:

x = "please don't share this: 234-604-1421"
x.split.last ~= /^\d{3}-\d{3}-\d{3}$/

but is there a way to match the sin otherwise?

Upvotes: 0

Views: 355

Answers (1)

zx81
zx81

Reputation: 41838

Another option worth considering for your rule is

(?<!\d)\d{3}-\d{3}-\d{3}(?!\d)

That way, if for any reason your phone number is followed or preceded by letters, as in

"please don't share this number234-604-142because it's private"

the regex will still work.

Explain Regex

(?<!                     # look behind to see if there is not:
  \d                     #   digits (0-9)
)                        # end of look-behind
\d{3}                    # digits (0-9) (3 times)
-                        # '-'
\d{3}                    # digits (0-9) (3 times)
-                        # '-'
\d{3}                    # digits (0-9) (3 times)
(?!                      # look ahead to see if there is not:
  \d                     #   digits (0-9)
)                        # end of look-ahead

Upvotes: 3

Related Questions