Reputation: 1
I have a string
str="TMOUT=1800; export TMOUT"
I want to extract only TMOUT=1800
from above string, but 1800
is not constant it can be any integer value. For example TMOUT=18
or TMOUT=201
etc. I'm very new to regular expression.
I tried using code below
re.search("TMOUT=\d",str).
It is not working. Please help
Upvotes: 0
Views: 57
Reputation: 2479
\d
matches a single digit. You want to match one or more digits, so you have to add a +
quantifier:
re.search("TMOUT=\d+", text)
If you then you want to extract the number you have to create a group using parenthesis ()
:
match = re.search(r"TMOUT=(\d+)", text)
number = int(match.group(1))
Or you may want to use the named group syntax (?P<name>)
:
match = re.search(r"TMOUT=(?P<num>\d+)", text)
number = int(match.group("num"))
I suggest you use regex101 to test your regexes and get an explanation of what they do. Also read python's re
docs to learn about the methods of the various objects and functions available.
Upvotes: 4