-1

I'm working on in a chatting group and I want to grab either the number or the name of the user who are sending the message.

I created a pattern to grab the phone number and I called patternnumber. I don't know how to use logical operators with patterns.

re.search(r'[a-zA-Z]{3,}','11/09/2017 21:46 - Robert: Hello world\n')

<re.Match object; span=(19, 25), match='Robert'>

However

re.search(patternnumber or r'[a-zA-Z]{3,}','11/09/2017 21:46 - Robert: Hello world\n')

Returns me nothing.

I've already tried to use | instead of 'or' but it gives an error. How can I solve this?

EDIT:

Following one of the answers below which solved my first problem partially, see:

re.search(r'patternnumber|[a-zA-Z]{3,}','11/09/2017 21:46 - Robert: Hello world\n')
<re.Match object; span=(19, 25), match='Robert'>

Okay, however when I add a phone number instead of a person's name, I have another problem:

patternnumber = r'(\(|\+)*\d{1,3}\)* \(*\d{2,5}\)* \d{2,7}((\-|\s)\d{2,5})*((\-|\s)\d{2,5})*'
re.search(r'patternnumber|[a-zA-Z]+','13/09/2017 22:10 - +55 85 8507-4394: Hello world\n')

<re.Match object; span=(37, 42), match='Hello'>
re.search(r'(\(|\+)*\d{1,3}\)* \(*\d{2,5}\)* \d{2,7}((\-|\s)\d{2,5})*((\-|\s)\d{2,5})*|[a-zA-Z]+','13/09/2017 22:10 - +99 99 9999-9999: Hello world\n')
<re.Match object; span=(19, 35), match='+99 99 9999-9999'>

Which should be the answer I expected.

I don't know what is happening, the pattern are the same, the difference is because one I created a variable before and the other I called it directly:

Red
  • 26,798
  • 7
  • 36
  • 58

2 Answers2

0

The reason your code didn't work is because the or statement gets evaluated before the search get initiated. The or statement will return the first non-empty string in it sees.

If the first string is empty and the second string is not, it will use the second string. If both aren't empty, it will take the first string. In this case, patternnumber is not an empty string, so it used patternnumber for the search, returning nothing.

Take the or out of the brackets:

re.search(patternnumber, '11/09/2017 21:46 - Robert: Hello world\n') or re.search(r'[a-zA-Z]{3,}','11/09/2017 21:46 - Robert: Hello world\n')
Red
  • 26,798
  • 7
  • 36
  • 58
0

You can use "|" operator in regular expressions.

re.search(r'(patternnumber|[a-zA-Z]{3,})','11/09/2017 21:46 - Robert: Hello world\n')

Where patternnumber should be the regular expression written out, not the variable.

imc
  • 952
  • 2
  • 8
  • 20