簡體   English   中英

Ruby和Null字符的正則表達式匹配

[英]Regular Expression Matching for Ruby and Null Characters

我需要為某個字符串匹配一個字符串,以便它也不會意外地與單詞匹配。 例如,假設我們要匹配字符串“ de”。 我希望它與以下字符串匹配:

"de"
" de"
"de "
" de "
" de  "
"I like the term de very much"

諸如此類的東西,但我不希望它與類似的字符串匹配

"dead"
" delaware"
"This is delaware"

等等。 有人可以用這樣的正則表達式幫助我嗎?

我認為/^\\s*de\\s*$/應該可以匹配' de '' de '字符串。 在這種情況下, ^匹配字符串的開頭, $ -字符串的結尾, \\s* -任何空格字符序列(可能為空),而de實際上就是您要查找的內容。

但是對於一般情況,單詞邊界有一個特殊符號- \\b 參見示例:

/de/ =~ ' de '       # matches
/de/ =~ ' rder '     # matches as well, but you don't want that

/\bde\b/ =~ 'de'         # matches
/\bde\b/ =~ 'qwe de rew' # matches as 'de' is a separate word
/\bde\b/ =~ ' rder '     # doesn't match as 'de' is not surrounded by word
                         # boundaries so it's not a separate word

您想匹配單詞de 為此,斷言它在單詞邊界處開始和結束:

\bde\b

我注意到您的示例僅由僅包含一個單詞的字符串組成(帶有可選的前導和尾隨空格)。 但是您的問題並未規定匹配的字符串必須僅包含一個單詞,因此尚不清楚這是否是必需條件。 上面的正則表達式將匹配包含單詞de字符串,無論字符串中是否還有其他單詞。 例如,此字符串將匹配:

"here come de judge"

該字符串將不會:

"here come der judge"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM