Home > Enterprise >  New to regex - retrieve a question mark
New to regex - retrieve a question mark

Time:07-09

I am quite new to regex and I would like to know if there was a way to match something that is either a normal character : \w or a question mark. I am trying to retrieve the value after the n.

The line has this format :

n : ?, t : 0.4

The thing that follows n can also be an integer :

n : 3, t : 0.7

So far I have :

import re
line = "n : 4, t : 0.4"
value = re.findall(r'\w : (\w ), \w : \d\.\d ', line)

How can I change this to take into account the fact that line can contain a question mark ?

Expected output :

  • if following n is a ?, value should be None
  • if following n is an integer, value should be that integer

CodePudding user response:

You want to use the "Alternate" regex symbol.

Your regex should therefore be: \w : (\w |\?), \w : \d\.\d . Do not forget to escape the question mark, since it is also a regex symbol.

EDIT: If the value following n must be either an integer or a ?, you can use \d to match a digit, and \d to match a number (with multiple digits). Your regex would become \w : (\d |\?), \w : \d\.\d

  • Related