How to use regex with optional characters in python?

后端 未结 5 674
离开以前
离开以前 2020-12-01 12:12

Say I have a string

\"3434.35353\"

and another string

\"3593\"

How do I make a single regular expression

5条回答
  •  失恋的感觉
    2020-12-01 12:41

    You can put a ? after a group of characters to make it optional.

    You want a dot followed by any number of digits \.\d+, grouped together (\.\d+), optionally (\.\d+)?. Stick that in your pattern:

    import re
    print re.match("(\d+(\.\d+)?)", "3434.35353").group(1)
    
    3434.35353
    
    print re.match("(\d+(\.\d+)?)", "3434").group(1)
    
    3434
    

提交回复
热议问题