Home  >  Q&A  >  body text

Python中re正则表达式的问题

str1 = 'universe  ['juːnɪvɜːs]'

请问下各位,怎么用正则表达式匹配 ['juːnɪvɜːs]

使之替换成空,最后的结果是:str1 = 'universe'

恳请各位不吝赐教,不胜感激。

黄舟黄舟2712 days ago401

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:42:14

    The answer above needs to be slightly modified. Regular Chinese square brackets [ ] themselves have grammatical meaning, so they need to be escaped. Just change it to this.

    pythonimport re
    str1 = re.sub(r'\[.*\]', '', "universe ['juːnɪvɜːs]")
    

    The official description of the python re module is as follows:

    https://docs.python.org/2/library/re.html

    Sometimes you forget to check the regular rules, they are quite detailed.

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:42:14

    import re
    str1 = re.sub(r'\[.*\]', '', "universe  ['juːnɪvɜːs]")
    

    Segmentfaults seems to automatically [escape to [, which forces me to use code blocks.

    reply
    0
  • Cancelreply