[英]How to search two consecutive characters in a string in python
I have a string我有一个字符串
x = Apple>Mango>+Orange
What I want is to output an error whenever the program sees in two consecutive character in which case the greater than (>) and the plus (+)我想要的是 output 每当程序在两个连续字符中看到错误时,在这种情况下大于(>)和加号(+)
I tried using the re.search method, but it seems like I cant put in two characters我尝试使用 re.search 方法,但似乎我不能输入两个字符
import re
x = "Apple>Mango>+Orange"
if re.search('>+', x):
print("error")
else:
print("no error")
When I run the program it always outputs error even though my output is Apple>Mango>Orange which should output no error since there's no consecutive characters in it.当我运行程序时,它总是输出错误,即使我的 output 是Apple>Mango>Orange这应该 output没有错误,因为其中没有连续的字符。 It seems like its treating only the character greater than (>) as it is.似乎它只处理大于 (>)的字符。
Is there a better way to do this, need help.有没有更好的方法来做到这一点,需要帮助。
As @ggorlen commented, when using regex patterns, some characters have special meaning.正如@ggorlen 评论的那样,在使用正则表达式模式时,某些字符具有特殊含义。 +
stands for as many matches as possible, it is a match-one-or-more quantifir, and if you wish to use it as a literal string, then you must escape it by preceding a backlash \
: +
代表尽可能多的匹配,它是一个匹配一个或多个的量词,如果你想将它用作文字字符串,那么你必须通过在反斜杠\
前面来转义它:
Therefore, the pattern to use would be:因此,要使用的模式是:
import re
x = "Apple>Mango>+Orange"
if re.search(r'>\+', x): #This pattern matches the literal strings ">+"
print("error")
else:
print("no error")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.