-1

I'm trying to do a regular expression match with special characters in it, such as "/", ".", and "-". This is the string:

17440 root      20   0 3645m 452m  12m S  152 11.8 347:32.04 test/1/02.3_4-6 

But the following code does not seem to match at the end with :

m=re.search(r"(?P<pid>\d+) +(?P<user>\w+) +(?P<pr>[\w-]+) +(?P<ni>[\w-]+) +(?P<virt>\w+) +(?P<res>\w+) +(?P<shr>\w+) +(?P<st>\w) +(?P<cpu>\d+) +(?P<mem>\d.+) +(?P<time>[0-9:.]+) +(?P<proc_name>[\w-/.]+)", line)

Do I need backslash before the special characters, such as "/" and "."? Thanks!

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
jessie wu
  • 7
  • 1
  • 1
  • 2

2 Answers2

0

You need to change (?P<mem>\d.+) in your regex to (?P<mem>[\d.]+) so that it would capture a digit or a dot one or more times or otherwise \d.+ would match a digit and the following characters greedily. Because there are some other patterns exists next to this +(?P<time>[0-9:.]+) +(?P<proc_name>[\w-/.]+), this (?P<mem>\d.+) would make the regex engine to backtrack in-order to find a match.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
-1

Yes, a period '.' is a special character.

Escape it with a back slash.

http://www.regular-expressions.info/characters.html