Python Regex doesn't work as expected

前端 未结 4 1955
别那么骄傲
别那么骄傲 2021-01-25 20:10

i\'ve crafted this regular expression:

\\\\n<(\\w+)>(.+?)\\\\n

to parse the foll

4条回答
  •  旧时难觅i
    2021-01-25 21:13

    Before the regex compiler sees a string, Python has already processed the slash-escapes, therefore you'd have to escape it twice (e.g. \\\\n for \\n). However, Python has a handy notation for exactly this sort of thing, just stick an r before the string:

    regex = re.compile(r"""\\n<(\w+)>(.+?)\\n""")
    

    By the way, I agree with the others here, do not use regexes to parse XML. However, hopefully you will find this string notation helpful in future regular expressions.

提交回复
热议问题