简体   繁体   English

匹配字符串ruby regex中的确切单词

[英]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? 但是有没有其他方法可以弥补罪过呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM