[英]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.