I am using python, and this regexp doesn't match, and I don't understand why.
string = "15++12"
if re.match("[-+*/][-+*/]+",string):
    # raise 开发者_如何学编程an error here
I am trying to raise an error, if one or more of "-","+","*","/" follows another one of those.
Use re.search() as re.match() only searches at the beginning of the string:
string = "15++12"
if re.search("[-+*/][-+*/]+",string):
    # raise an error here
Also, this could be simplified to:
string = "15++12"
if re.search("[-+*/]{2,}",string):
    # raise an error here
as the {2,} operator searches for two or more of the previous class.
re.match tries to match from the beginning of the string. To match any substring, either use re.search or put a .* before the pattern:
>>> re.match("[-+*/][-+*/]+", s)
>>> re.search("[-+*/][-+*/]+", s)
<_sre.SRE_Match object at 0x7f5639474780>
>>> re.match(".*[-+*/][-+*/]+", '15++12')
<_sre.SRE_Match object at 0x7f5639404c60>
I believe it is because re.match matches only the beginning of the string. Try re.search or re.findall
Check out 7.2.2 at python docs: http://docs.python.org/library/re.html
Python violates the Principle of Least Surprise here: they've chosen a word with an established meaning and warped it into meaning something different from that. This isn't quite evil and wrong, but it is certainly stupid and wrong. – tchrist @tchrist
I don't agree. In fact, I think exactly the contrary, it isn't stupid
If I say :
a regex's pattern
"\d+[abc]"matches the string '145caba'
everybody will agree with this assertion.
If I say :
a regex's pattern
"\d+[abc]"matches the string 'ref/ 789lomono 145abaca ubulutatouti'
80 % of people will agree and the other rigorous 20 % of people, in which I am, will be unsatisfied by the wording and will reclaim that the expression be changed to :
"\d+[abc]"matches SOMEWHERE in the string 'ref/ 789lomono 145abaca ubulutatouti'
That's why I find justified to call an action that consists to search if and where a pattern matches in a string: search()  
and to call the action to verify if a match occurs from the beginning: match()    
For me it's very much logical, not surprising
.
PS
A former answer of mine have been deleted. As I don't know how to write to the author of the deletion to ask him the reason why he judged my former answer being a rant (!!!?), I re-post what seems to me absolutely impossible to be qualified so
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论