python编写正则表达式匹配单词_Python正则表达式匹配整个单词
守候你守候我
我認為,通過給出的答案,OP所期望的行為并沒有完全實現。具體來說,布爾值的期望輸出沒有完成。給出的答案做幫助說明這一概念,我認為他們是優秀的。也許我可以說明我的意思,我認為OP使用了下面的例子。給出的繩子是,a = "this is a sample"“任擇議定書”接著說,我想匹配整個單詞-例如匹配"hi"應該回來False自"hi"不是一個詞.。據我所知,引用的是搜索標記,"hi"正如世界上所發現的,"this"..如果有人搜索字符串,a為單詞 "hi",他們應該接受False作為回應。行動還在繼續,..和"is"應該回來True因為左邊和右邊沒有阿爾法字符。在本例中,引用是對搜索令牌的引用。"is"就像在單詞中找到的那樣"is"..我希望這有助于澄清為什么我們使用單詞邊界。其他答案的行為是“不返回一個單詞,除非這個詞是自己找到的-而不是在其他單詞的內部。”“詞界”速記字符類做得很好。只有這個詞"is"到目前為止已經在例子中使用過了。我認為這些答案是正確的,但我認為有更多的問題的根本意義,需要解決。為了理解這個概念,應該注意其他搜索字符串的行為。換句話說,我們需要泛化@Georg給出的(極好的)答案re.match(r"\bis\b", your_string)同r"\bis\b"@Omprakash的回答中也使用了概念,他以如下方式開始了一般性討論>>> y="this isis a sample.">>> regex=re.compile(r"\bis\b")? # For ignore case: re.compile(r"\bis\b", re.IGNORECASE)>>> regex.findall(y)[]假設應該顯示我討論過的行為的方法是find_only_whole_word(search_string, input_string)然后,應該期望出現以下行為。>>> a = "this is a sample">>> find_only_whole_word("hi", a)False>>> find_only_whole_word("is", a)True再一次,我就是這樣理解OP的問題的。我們通過@Georg的回答向這種行為邁出了一步,但這有點難以理解/實現。風趣>>> import re>>> a = "this is a sample">>> re.search(r"\bis\b", a)<_sre.SRE_Match object; span=(5, 7), match='is'>>>> re.search(r"\bhi\b", a)>>>第二個命令沒有輸出。@OmPrakesh給出的有用答案顯示了輸出,但沒有顯示輸出。True或False.下面是一個更完整的行為樣本。>>> find_only_whole_word("this", a)True>>> find_only_whole_word("is", a)True>>> find_only_whole_word("a", a)True>>> find_only_whole_word("sample", a)True# Use "ample", part of the word, "sample": (s)ample>>> find_only_whole_word("ample", a)False# (t)his>>> find_only_whole_word("his", a)False# (sa)mpl(e)>>> find_only_whole_word("mpl", a)False# Any random word>>> find_only_whole_word("applesauce", a)False>>>這可以通過以下代碼實現:#!/usr/bin/env python3# -*- coding: utf-8 -*-##@file find_only_whole_word.pyimport redef find_only_whole_word(search_string, input_string):? # Create a raw string with word boundaries from the user's input_string? raw_search_string = r"\b" + search_string + r"\b"? match_output = re.search(raw_search_string, input_string)? ##As noted by @OmPrakesh, if you want to ignore case, uncomment? ##the next two lines? #match_output = re.search(raw_search_string, input_string,?? #? ? ? ? ? ? ? ? ? ? ? ? ?flags=re.IGNORECASE)? no_match_was_found = ( match_output is None )? if no_match_was_found:? ? return False? else:? ? return True##endof:? find_only_whole_word(search_string, input_string)下面是一個簡單的演示。從保存文件的同一目錄運行Python解釋器,find_only_whole_word.py.>>> from find_only_whole_word import find_only_whole_word>>> a = "this is a sample">>> find_only_whole_word("hi", a)False>>> find_only_whole_word("is", a)True>>> find_only_whole_word("cucumber", a)False# The excellent example from @OmPrakash>>> find_only_whole_word("is", "this isis a sample")False>>>
總結
以上是生活随笔為你收集整理的python编写正则表达式匹配单词_Python正则表达式匹配整个单词的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python frame用法_pytho
- 下一篇: 安卓平板运行python_使用Pytho