Divide string by line break or period with Python regular expressions

后端 未结 5 1273
逝去的感伤
逝去的感伤 2020-12-17 10:31

I have a string:

\"\"\"Hello. It\'s good to meet you.
My name is Bob.\"\"\"

I\'m trying to find the best way to split this into a list divi

相关标签:
5条回答
  • 2020-12-17 11:00

    You can use this split

    re.split(r"(?<!^)\s*[.\n]+\s*(?!$)", s)
    
    0 讨论(0)
  • 2020-12-17 11:07

    You don't need regex.

    >>> txt = """Hello. It's good to meet you.
    ... My name is Bob."""
    >>> txt.split('.')
    ['Hello', " It's good to meet you", '\nMy name is Bob', '']
    >>> [x for x in map(str.strip, txt.split('.')) if x]
    ['Hello', "It's good to meet you", 'My name is Bob']
    
    0 讨论(0)
  • 2020-12-17 11:18
    >>> s = """Hello. It's good to meet you.
    ... My name is Bob."""
    >>> import re
    >>> p = re.compile(r'[^\s\.][^\.\n]+')
    >>> p.findall(s)
    ['Hello', "It's good to meet you", 'My name is Bob']
    >>> s = "Hello. #It's good to meet you # .'"
    >>> p.findall(s)
    ['Hello', "#It's good to meet you # "]
    
    0 讨论(0)
  • 2020-12-17 11:19

    For your example, it would suffice to split on dots, optionally followed by whitespace (and to ignore empty results):

    >>> s = """Hello. It's good to meet you.
    ... My name is Bob."""
    >>> import re
    >>> re.split(r"\.\s*", s)
    ['Hello', "It's good to meet you", 'My name is Bob', '']
    

    In real life, you'd have to handle Mr. Orange, Dr. Greene and George W. Bush, though...

    0 讨论(0)
  • 2020-12-17 11:20

    Mine:

    re.findall('(?=\S)[^.\n]+(?<=\S)',su)
    
    0 讨论(0)
提交回复
热议问题