Prashant Pathak
Prashant Pathak

Reputation: 173

Searching specific string using regex in python

I have a string

import re
name = 'simranjeet kumar'

print (re.findall(r'^s.', name))

output: ['si']

But I am expecting ['simranjeet'],may I know why I am not getting simranjeet and why I am getting only ['si'] I mean string of length 2.

Upvotes: 0

Views: 84

Answers (1)

Fomalhaut
Fomalhaut

Reputation: 9727

In regular expressions . means any ONE symbol. To extract MANY any symbols use + or *. You are extracting a word until the space. I would solve this task like this:

re.findall(r'^(.+?)\s', name)
# or
re.findall(r'^(s.+?)\s', name)
# or
re.findall(r'^(\S+)', name)
# or
re.findall(r'^(s\S+)', name)

\s means any space symbol. \S means any non-space symbol. See wikipedia for more information.

Upvotes: 1

Related Questions