正则表达式区别+和*
Regular expression difference + and *
这可能是一个转储问题。但我要问清楚。
我有一条短信
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 0r 多次出现究竟是什么意思。任何人都可以解释为什么当我们使用 *.
时它在单词之间 space
`*` matches an empty string as well.
所以Ne
之间有一个空的string.So会被space代替。
*
是零次或多次出现,零表示空
+
是一个或多个Occurrence,它至少匹配一个
+
如何匹配字符串
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
这可能是一个转储问题。但我要问清楚。
我有一条短信
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 0r 多次出现究竟是什么意思。任何人都可以解释为什么当我们使用 *.
时它在单词之间 space`*` matches an empty string as well.
所以Ne
之间有一个空的string.So会被space代替。
*
是零次或多次出现,零表示空
+
是一个或多个Occurrence,它至少匹配一个
+
如何匹配字符串
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