Shivam Gupta Shivam Gupta - 9 months ago 38
Python Question

Need help in the Regular Expression start with string with space

I want the string start with "shivam " (without quote).my regular expression is :


but they are not matching space after shivam what do i do?

Input is:

shivam gupta

Expected output is:


Without any space both side. My output is
shivam gupta

Answer Source

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( # 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(" "):])

Another demo.