Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式从给定起始和结束子字符串的单词列表中搜索字符串,其中缺少一个字母_Python_Regex_String - Fatal编程技术网

Python 使用正则表达式从给定起始和结束子字符串的单词列表中搜索字符串,其中缺少一个字母

Python 使用正则表达式从给定起始和结束子字符串的单词列表中搜索字符串,其中缺少一个字母,python,regex,string,Python,Regex,String,给定一个完整的可能单词列表,我想获得一个给定该单词开头和结尾子字符串的单词列表,其中只缺少一个字母,例如: 给定起始子串e和结束子串r,我想获得ear,err 给定起始子串和结束子串am,我想得到ham,bam 给定起始子串ha和结束子串,我想获得火腿、帽子 我在想,使用regex是否可能做到这一点。是的,您可以将它与regex一起使用 import re txt = ["earrr","ear","eorrr","ealo

给定一个完整的可能单词列表,我想获得一个给定该单词开头和结尾子字符串的单词列表,其中只缺少一个字母,例如:

给定起始子串e和结束子串r,我想获得ear,err

给定起始子串和结束子串am,我想得到ham,bam

给定起始子串ha和结束子串,我想获得火腿、帽子


我在想,使用regex是否可能做到这一点。

是的,您可以将它与regex一起使用

import re

txt = ["earrr","ear","eorrr","ealor"]
for i in txt :
    x = re.search("^e.*r$", i)
    print(x)

# ^ means it starts with a particular char, in this case it starts with e
#. means Any character (except newline character)
# * means it can be followed by multiple character
# $ means it ends with, in this case it ends with r
对于第二种情况,您可以这样做

import re
txt = "ham"
x = re.search(".*am$", txt)
x
import re

txt = "ham"
x = re.search("^ha.*[a-zA-Z]", txt)
x
第三个,你可以这样做

import re
txt = "ham"
x = re.search(".*am$", txt)
x
import re

txt = "ham"
x = re.search("^ha.*[a-zA-Z]", txt)
x
或者你可以这样做

x = re.search("^ha.*", txt)
x
有关更多信息,请访问此网站
很抱歉,这有点混乱,我第一次在stackoverflow中写作。

如果ha和``匹配帽子,他们是否也应该匹配halt?i、 这里是否也有一个概念通配符,比如在ear中?基本上,如果用一个代表一个字符通配符的点替换空格并连接子字符串,那么基本上就是正则表达式。您可能希望在第一个子字符串之前添加^1,在第二个子字符串之后添加$1,并在它们之间添加。*@Balduin给定前面和后面的子字符串,我只能再添加一个字符。看起来像^front substring.end substring$对我有用,谢谢:注意根据注释,子字符串之间只能有一个字符,所以应该是这样。而不是*