Reputation:
I'm trying to extract a pattern from string using python regex. But it is not working with the below pattern
headerRegex = re.compile(r'^[^ ]*\s+\d*')
mo = headerRegex.search(string)
return mo.group()
My requirment is regular expression that should start with anything except white space and followed by one or more whitespace then digits occurence one or more
Example
i/p: test 7895 => olp:7895(correct)
i/p: 8545 ==> Not matching
i/p: @#@# 3453 ==>3453
May I know what is missing in my regex to implement this requirement?
Upvotes: 0
Views: 856
Reputation: 163362
In the pattern that you tried, only matching whitespace chars is mandatory, and you might possibly also match only newlines.
Change the quantifiers to + to match 1+ times, and if you don't want to match newlines as well use [^\S\r\n]+
instead.
If that exact match is only allowed, add an anchor $
to assert the end of the string, or add \Z
if there is no newline following allowed.
^\S+[^\S\r\n]+\d+$
^
Start of string\S+
Match 1+ times a non whitespace char[^\S\r\n]+
Match 1+ times a whitespace char except newlines\d+
Match 1+ digits$
End of stringUpvotes: 1