[英]How to do regex check if a list of substrings appears before a string?
I have tried to searched it but no specific answer. 我试图搜索它,但没有具体答案。
I would like to identify the string I want to use depending on the characters appears before it. 我想根据前面出现的字符来确定要使用的字符串。
What I like to do is, For example: 我想做的是,例如:
def check_if_char_appears(input_string):
substring_list = ['aa', 'bb', 'dd', 'ef']
for i in substring_list:
if i appears right before 'cake':
return True
return False
result: Condition1: 结果:Condition1:
input_string = 'aacake'
check_if_char_appears(input_string)
is True 是真的
Condition2: 条件2:
input_string = 'aakkcake'
check_if_char_appears(input_string)
is False 是错误的
found the java solution could do the funcion "if i appears before 'cake':" 发现Java解决方案可以完成功能“如果我出现在'cake'之前:”
str.matches("i*(?<!\\.)cake.*");
but I dont know how to do with python the this function.. could some one kindly help me with this (or tell me how to look this up in google?) 但我不知道如何使用python这个功能..有人可以帮我这个问题(或告诉我如何在Google中查找吗?)
Thanks! 谢谢!
for simple case like yours. 对于像您这样的简单案例。
substring_list = ['aa', 'bb', 'dd', 'ef']
for i in substring_list:
if "{}cake".format(i) in input_string:
return True
Using regex 使用正则表达式
matches = re.match(r'.*(aa|bb|dd|ef)cake.*', your_str)
if matches:
# do whatever you want
If you want nothing after the cake
如果你在cake
之后什么都不想要
matches = re.match(r'.*(aa|bb|dd|ef)cake', your_str)
if matches:
# do whatever you want
You can use regex here. 您可以在这里使用正则表达式。 you can make regex on the go like. 您可以随时随地制作正则表达式。
substring_list = ['aa', 'bb', 'dd', 'ef']
if re.match(r"({})cake".format("|".join(substring_list)), input_string):
return True
long answer: 长答案:
def check_if_char_appears(input_string):
substring_list = ['aa', 'bb', 'dd', 'ef']
sub_string_re = "|".join(substring_list) # 'aa|bb|dd|ef'
re_string = r"({})cake".format(sub_string_re) # (aa|bb|dd|ef)cake
if re.match(re_string, input_string):
return True
return False
input_string = 'aacake'
print(check_if_char_appears(input_string))
input_string = 'aakkcake'
print(check_if_char_appears(input_string))
out: 出:
True
False
There is a regex module in python ( https://docs.python.org/3.6/library/re.html ) python中有一个正则表达式模块( https://docs.python.org/3.6/library/re.html )
That should do exactly the same thing just with 那应该做完全一样的事情
import re
m = re.search("i*(?<!\\.)cake.*", your_string)
for match in m:
print(m)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.