[英]Regex that matches a word bound by start and end of a string or non-word characters
[英]Regex in python that matches a word containing 'z', not at the start or end of the word
考慮一個句子,其中包含一些可能以“z”開頭或結尾的單詞。
這是我的代碼:
reg_9 = re.compile(r'\b[^z]\w+z\w+[^z]\b')
sentence = "this sentence contains zatstart azb pole ab noaz yeszishere z_is_op"
reg_9.findall(sentence)
所以根據上面的正則表達式邊界'\ b'內的所有字符串,它不以'z'開頭並且不以'z'結尾(在開始和結束時的[^z])但在其之間的某處有'z'在我的正則表達式中由 '\w+z\w+' 給出。
在 output 我得到這個:
[' azb ', ' yeszishere ']
那么有人能說出為什么這個 output 字符串在開頭和結尾包含那些額外的空格嗎?
您需要使\w+
可選,即改用\w*
。 但是,我會將您的正則表達式表述為:
reg_9 = re.compile(r'\b[^\WzZ]\w*z\w*[^\WzZ]\b')
sentence = "this sentence contains zatstart azb pole ab noaz yeszishere z_is_op"
print(reg_9.findall(sentence)) # ['azb', 'yeszishere']
這個正則表達式模式說:
\b match a word boundary
[^\WzZ] match any word character OTHER than z or Z
\w* zero or more word characters
z z
\w* zero or more word characters
[^\WzZ] match any word character OTHER than z or Z
\b match a word boundary
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.