简体   繁体   English

在re.search中使用“|”的TypeError(“RE”|“RE”|“RE”,字符串)

[英]TypeError from use of “|” in re.search(“RE”|“RE”|“RE”, string)

According to the docs, "|" 根据文档,“|” can be used to create a regular expression that matches either of the patterns separated by "|". 可用于创建匹配由“|”分隔的任一模式的正则表达式。

I am trying to use the following to see if moves contains a string that matches one of "UP""DOWN""LEFT""RIGHT": 我试图使用以下内容来查看移动是否包含一个匹配“UP”“DOWN”“LEFT”“RIGHT”之一的字符串:

moves = input("UP 9")
m = re.search("UP"|"DOWN"|"LEFT"|"RIGHT", moves)

But I keep getting the "TypeError: unsupported operand type(s) for |: 'str' and 'str'" . 但我继续得到"TypeError: unsupported operand type(s) for |: 'str' and 'str'" How to fix it? 怎么解决?

I tried looking online but there are few samples that show the use of "|" 我尝试在线查看,但很少有样本显示使用“|” in re. 在重新。 Is it not commonly used for some reason? 它是不是出于某种原因常用?

This is, unfortunately a typo, but the answer goes a little deeper than that. 不幸的是,这是一个错字,但答案比这更深刻。

| is the bitwise OR operator. 是按位OR运算符。 It is defined for integers only, not strings. 它仅针对整数定义,而不是字符串。 On the other hand, the "|" 另一方面, "|" character (note the quotes) is the regex OR pipe, and is used to specify a conjunction on patterns. character(注意引号)是正则表达式OR管道,用于指定模式的连接。

In summary, the | 总之, | needs to be inside the pattern string, not outside. 需要在模式字符串内,而不是在外面。

m = re.search("UP|DOWN|LEFT|RIGHT", moves)

For more information on the various constructs available in regular expression mini-language, see the official Regular Expression HOWTO . 有关正则表达式迷你语言中可用的各种结构的更多信息,请参阅官方正则表达式HOWTO The subsection on Regex Metacharacters , in particular (which explains the use of the OR pipe amongst others) should be helpful. 特别是关于Regex Metacharacters的小节(其中解释了OR管道的使用)应该是有帮助的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM