简体   繁体   English

在单引号正则表达式和python之间提取短语

[英]extract phrase between single quotes regex and python

I want to extract from text phrases which are usually between single quotation我想从通常在单引号之间的文本短语中提取

def extract_phrase(s):
    list = []
    pattern = re.compile("(?<=')[^']+(?=')")
    for value in pattern.findall(s):
        list.append(value)
    return list

print(extract_phrase("I can't Sleep and 'black lives matter'"))
['t Sleep and ', 'black lives matter']

as you can see the code return 2 strings, which is not good because I want only the 'black lives matter' to return.如您所见,代码返回 2 个字符串,这并不好,因为我只想返回“黑人的命也是命”。

to fix it I tried to put \\b at the start and in the end of the regex expression but i did not recieve anything when i made that change.为了解决这个问题,我尝试将 \\b 放在正则表达式的开头和结尾,但是当我进行更改时我没有收到任何信息。

so how can i change the regex statement so i will get all strings from text that start with ' and end with '.那么如何更改正则表达式语句,以便从文本中获取所有以 ' 开头并以 ' 结尾的字符串。

thank you谢谢你

If your single quotes are all balanced and unescaped then you may use this regex:如果您的单引号都是平衡且未转义的,那么您可以使用此正则表达式:

\B'.*?'(?!\w)

RegEx Demo正则表达式演示

RegEx Details:正则表达式详情:

  • \\B : Asserts position where \\b does not match \\B :断言\\b不匹配的位置
  • ' matches the character ' '匹配字符'
  • .*? : Matches 0 or more of any character : 匹配 0 个或多个任意字符
  • (?!\\w) : Negative lookahead to assert that next character is not a word character (?!\\w) :否定前瞻断言下一个字符不是单词字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM