2015-01-02 100 views
-2

這可能是一個轉儲問題。但我必須要求澄清它。正則表達式差異+和*

我有一個文本

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

文本被有意分散。我偶然發現了這個疑問。

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 

看看下一條語句。

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 

唯一的區別是*和+。那麼,到底什麼意思是0或更多的出現和更多的出現。任何人都可以解釋爲什麼當我們使用*時,單詞之間的空格。

回答

2

如何+匹配字符串

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+ 

**如何匹配字符串

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 
+1

這是任何人都可以給出的最好解釋。它的好答案很好地解釋了。 – user3116355

+0

謝謝!!! :) – nu11p01n73R

1
`*` matches an empty string as well. 

因此在Ne之間有一個空字符串。所以它會被空格替換。

+0

@這是一個新的信息。很有幫助。非常感謝。 – user3116355

+0

但是,我們怎麼能說*只匹配空間出現呢?它找到了實際上不存在的單詞之間的空格。 – user3116355

+0

@ user3116355它發現「一串空白的空格」。 – vks

0

*是零個或更多次數,零表示空

+是一個或多個Ocuurance,它匹配至少一個

+0

但我想匹配所有空間。但是,我們怎麼能說*只匹配空間的出現呢?它找到了實際上不存在的單詞之間的空間。 – user3116355