[英]How to find a “piece” of word in a string with regex and using it in python?
[英]Python Find entire word in string using regex and user input
我正在嘗試使用正則表達式查找整個單詞,但是我正在搜索的單詞是來自用戶輸入的變量值。 我已經試過了:
regex = r"\b(?=\w)" + re.escape(user_input) + r"\b"
if re.match(regex, string_to_search[i], re.IGNORECASE):
<some code>...
但它匹配每次出現的字符串。 它匹配正確的“ var”->“ var”,但也匹配“ var”->“ var” iable,我只希望它匹配“ var”->“ var”或“ string”->“ string”
輸入:“劍”
String_to_search =“曾經有位造劍的劍匠”
所需的輸出:將“ sword”匹配到“ sword”,而不是“ swordsmith”
您可以像這樣嘗試re.finditer:
>>> import re
>>> user_input = "var"
>>> text = "var variable var variable"
>>> regex = r"(?=\b%s\b)" % re.escape(user_input)
>>> [m.start() for m in re.finditer(regex, text)]
[0, 13]
它將迭代找到所有匹配項。
您似乎想使用與整個字符串匹配的模式。 請注意,當您想查找部分匹配項時,需要\\b
字邊界。 如果需要完整的字符串匹配,則需要anchors 。 由於re.match
將匹配re.match
錨定在字符串的開頭,因此您所需要的就是$
(字符串結尾的位置)在模式的末尾:
regex = '{}$'.format(re.escape(user_input))
然后使用
re.match(regex, search_string, re.IGNORCASE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.