Python 3.7.4: 're.error: bad escape \s at position 0'

前端 未结 4 631
耶瑟儿~
耶瑟儿~ 2020-12-20 07:05

My program looks something like this:

import re
# Escape the string, in case it happens to have re metacharacters
my_str = \"The quick brown fox jumped\"
esc         


        
4条回答
  •  感动是毒
    2020-12-20 07:20

    I guess you might be trying to do:

    import re
    # Escape the string, in case it happens to have re metacharacters
    my_str = "The\\ quick\\ brown\\ fox\\ jumped"
    escaped_str = re.escape(my_str)
    # "The\\ quick\\ brown\\ fox\\ jumped"
    # Replace escaped space patterns with a generic white space pattern
    print(re.sub(r"\\\\\\\s+", " ", escaped_str))
    

    Output 1

    The quick brown fox jumped
    

    If you might want to have literal \s+, then try this answer or maybe:

    import re
    # Escape the string, in case it happens to have re metacharacters
    my_str = "The\\ quick\\ brown\\ fox\\ jumped"
    escaped_str = re.escape(my_str)
    print(re.sub(r"\\\\\\\s+", re.escape(r"\s") + '+', escaped_str))
    

    Output 2

    The\s+quick\s+brown\s+fox\s+jumped
    

    Or maybe:

    import re
    # Escape the string, in case it happens to have re metacharacters
    my_str = "The\\ quick\\ brown\\ fox\\ jumped"
    print(re.sub(r"\s+", "s+", my_str))
    

    Output 3

    The\s+quick\s+brown\s+fox\s+jumped
    

    If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


    RegEx Circuit

    jex.im visualizes regular expressions:

    Demo

提交回复
热议问题