-3

This may be a dump question. But I have to ask to clarify it.

I have a text

string = ''' t Network Questions
Is there         something like a (readied) charge in 5e?
 Can you use a
  Bonus Action on a       turn'''

The text is scattered purposefully. i came across this doubt accidentally.

print re.sub(r'\s+',' ',string)

 t Network Questions Is there something like a (readied) charge in 5e? Can you use a Bonus Action on     a turn

Have a look at the next statement.

 print re.sub(r'\s*',' ',string)

 t N e t w o r k Q u e s t i o n s I s t h e r e s o m e t h i n g l i k e a ( r e a d i e d ) c h a r g e i n 5 e ? C a n y o u u s e a B o n u s A c t i o n o n a t u r n

The only difference is * and +. So, what exactly it is meant by 0 or more occurrence and 1 0r more occurrence. Can anyone explain why its space between words when we are using *.

glglgl
  • 89,107
  • 13
  • 149
  • 217
user3116355
  • 1,187
  • 3
  • 14
  • 17

3 Answers3

2

How does + matches the string

Is there         something like
  |
 \s #one space

Is there         something like
        |
       \s+ #one or more space 

Is there         something like
         |
        \s+ #one or more space

# And so on untile

Is there         something like
                |
               \s+

How does ** matches the string

Is there         something like
|
\s* #matches here. Because there is zero occurence of space (Before the character I)

Is there         something like
 |
 \s* # matches here as well and so on in all the characters

     #  Here it doesnt match any character, Rather it matches the postion between I and s as there is zero occurence of \s
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
1
`*` matches an empty string as well.

So between Ne there is one empty string.So it will be replace by space.

vks
  • 67,027
  • 10
  • 91
  • 124
0

* is zero or more Occurance , zero means empty

+ is one or more Ocuurance, it matches at least one

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
  • But i am trying to match all spaces. But how can we say that * matches only space occurences It finds space between words which are actually not there. – user3116355 Jan 02 '15 at 17:40