Reputation: 82
I want the string start with "shivam " (without quote).my regular expression is :(?=shivam\s)\w+
but they are not matching space after shivam what do i do?
Input is:
shivam gupta
Expected output is:
gupta
Without any space both side. My output is shivam gupta
.
Upvotes: 1
Views: 44
Reputation: 627410
If you want to learn a bit of a regex use
import re
s = "shivam gupta"
m = re.match(r"shivam\s+(\w+)$", s)
if m: # Check if the pattern matches the string
print(m.group(1)) # print only Group 1 contents
See the Python demo
The re.match
method only searches at the start of string, so shivam
is looked for at the start. Then \s+
matches one or more whitespaces, and finally, (\w+)$
matches and captures into Group 1 one or more word chars and then the end of string $
.
The Group 1 contents are accessed via .group(1)
of the match object (here, m
).
However, you can use string methods and a split operation here:
s = "shivam gupta"
if s.startswith("shivam "):
print(s.split()[1]) # or even print(s[s.find(" "):])
Upvotes: 2