Special work "*" in a regular expression expression

When writing a regex pattern to replace all the continuums '1 and singles' 1 as 's'. I found this rather confusing, using "+" (used to match 1 or more) gave the expected result, but "*" gave a weird result

>>> l='100'
>>> import re
>>> j=re.compile(r'(1)*')    
>>> m=j.sub('*',l)
>>> m
'*0*0*'

While using '+' gave the expected result.

>>> l='100'
>>> j=re.compile(r'1+')
>>> m=j.sub('*',l)
>>> m
'*00'

as '*' does in regex, and its behavior must match 0 or more.

+6
source share
3 answers

(1)* " 0 1". , 100 1, 0 0 0. "*". 1+ 1 , .

, , python *0*0*, **0*0*. python script . (Regex101 , python. - Regex PCRE ( PHP Apache HTTP Server) . !)

JavaScript **0*0* ( 1 0 ). , " ". . ( , 0 )

console.log("100".replace(/(1)*/g, '*'))
Hide result
+5

, . , . , Perl.

$ perl -e'CORE::say "100" =~ s/1*/\*/rg'
**0*0*
  • 0 1 .
  • 1 0 .
  • [ , ]
  • 2 0 .
  • [ , ]
  • 3 0 .
  • [ , ]
  • [Fail to match: Beyond end of string]
+2
regex = r"1*"
p = re.compile(regex)
test_str = "100"
for m in p.finditer(test_str):
    print(m.start(), m.group())

4 ( regex101 4 ):

0 1
1 
2 
3 

re.sub() 3 , re.sub() (Python doc):

sub (pattern, repl, string, count = 0, flags = 0)

, .

...

, , sub('x*', '-', 'abc') '-a-b-c-'.

? , :

, . , .

, , - , .

1 0 , , .

+2

All Articles