正则表达式差异+和*

时间:2015-01-02 17:32:01

标签: python regex

这可能是转储问题。但我必须要求澄清它。

我有一个文字

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次或更多次出现和1次多次出现。当我们使用*时,任何人都能解释为什么它之间的空格。

3 个答案:

答案 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 :(得分:1)

`*` matches an empty string as well.

所以在Ne之间有一个空字符串。所以它将被空格替换。

答案 2 :(得分:0)

*为零或更多Occurance,零表示空

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

相关问题