How to conditional regex

前端 未结 4 467
无人及你
无人及你 2020-12-31 14:53

I want a regex that does one thing if it has 3 instances of .in the string, and something else if it has more than 3 instances.

for example



        
4条回答
  •  借酒劲吻你
    2020-12-31 15:45

    In Python (excuse me; but regexes are without language frontier)

    import re
    
    regx = re.compile('^([^.]*?\.){3}[^.]*?\.')
    
    for ss in ("aaa.bbb.ccc",
               "aaa.bbb.ccc.ffffd",
               'aaa.bbb.ccc.ffffd.eee',
               'a.b.c.d.e.f.g.h.i...'):
      if regx.search(ss):
        print ss + '     has at least 4 dots in it'
      else:
        print ss + '     has a maximum of 3 dots in it'
    

    result

    aaa.bbb.ccc     has a maximum of 3 dots in it
    aaa.bbb.ccc.ffffd     has a maximum of 3 dots in it
    aaa.bbb.ccc.ffffd.eee     has at least 4 dots in it
    a.b.c.d.e.f.g.h.i...     has at least 4 dots in it
    

    This regex' pattern doesn't require that the entire string be analysed (no symbol $ in it). It's better on long strings.

提交回复
热议问题