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":
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'". 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. 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.
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. The subsection on Regex Metacharacters, in particular (which explains the use of the OR pipe amongst others) should be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With