繁体   English   中英

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

[英]Match exact word in string ruby regex

我的红宝石上有这串琴弦,我正努力与罪恶相称

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

到目前为止,我有

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

但这也将与第二种情况匹配。 在开始和结束处加上^和$将导致此功能根本无法起作用。

要解决这个问题,我可以这样做:

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

但是有没有其他方法可以弥补罪过呢?

值得考虑的另一种选择是

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

这样,无论出于何种原因,您的电话号码都以字母开头或后跟,例如

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

正则表达式仍然可以使用。

解释正则表达式

(?<!                     # 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