【问题标题】:Extract text between quotation using regex python使用正则表达式python在引号之间提取文本
【发布时间】:2021-10-12 15:12:23
【问题描述】:

我尝试在引号“”中提取文本

file content:
"abc"
"ABC. XYZ"
"1 - 2 - 3"

我尝试过使用正则表达式的代码

title = re.findall(r'\"(.+?)\"', filecontent)
print(title)

输出:

['abc']
[] # Some lines comes out like this empty
['1 - 2 - 3']

有些行是空的,不知道为什么。有没有其他更好的方法来做到这一点?

【问题讨论】:

标签: python regex


【解决方案1】:

如果你想从一个字符串中提取一些子字符串,你可以去re.search

演示:

import re

str_list = ['"abc"', '"ABC. XYZ"', '"1 - 2 - 3"']

for str in str_list:
    search_str = re.search('"(.+?)"', str)
    if search_str:
        print(search_str.group(1))

输出:

abc
ABC. XYZ
1 - 2 - 3

【讨论】:

    【解决方案2】:

    IIUC,你试试这个吗?

    filecontent = '''
    "abc"
    "ABC. XYZ"
    "1 - 2 - 3"
    '''
    
    re.findall(r'\"(.+?)\"', filecontent)
    

    输出:

    ['abc', 'ABC. XYZ', '1 - 2 - 3']
    

    【讨论】:

      【解决方案3】:

      我的解决办法是:

      import re
      my_strings = ['SetVariables "a" "b" "c" ', 'd2efw   f "first" +&%#$%"second",vwrfhir, d2e   u"third" dwedew', '"uno"?>P>MNUIHUH~!@#$%^&*()_+=0trewq"due"        "tre"fef    fre f', '       "uno""dos"      "tres"', '"unu""doua""trei"', '      "um"                    "dois"           "tres"                  ']
      my_substrings = []
      for current_test_string in my_strings:
          for values in re.findall(r'\"(.+?)\"', current_test_string):
              my_substrings.append(values)
              #print("values are:",values,"=")
          print(" my_substrings are:",my_substrings,"=")
          my_substrings = []
      

      要使用的替代正则表达式是:

      • re.findall('"(.+?)"', current_test_string) [Avinash2021] [user17405772021]
      • re.findall('"(.*?)"', current_test_string) [Shelvington2020]
      • re.findall(r'"(.*?)"', current_test_string) [Lundberg2012] [Avinash2021]
      • re.findall(r'"(.+?)"', current_test_string) [Lundberg2012] [Avinash2021]
      • re.findall(r'"["]', current_test_string) [Muthupandi2019]
      • re.findall(r'"([^"]*)"', current_test_string) [Pieters2014]
      • re.findall(r'"(?:(?:(?!(?
      • re.findall(r'"(.*?)(?
      • re.findall('"[^"]*"', current_test_string) # 导致双引号保留在字符串中,但可以通过其他方式删除。[Martelli2013]
      • re.findall('"([^"]*)"', current_test_string) [jspcal2014]
      • re.findall("'(.*?)'", current_test_string) [akhilmd2016]

      current_test_string.split("\"") 方法适用于字符串具有其中子字符串嵌入引号内的模式。 这是因为它在本例中使用双引号作为分隔符来标记字符串,并接受未嵌入双引号内的子字符串作为从字符串中提取的有效子字符串。

      参考资料:

      【讨论】:

        猜你喜欢
        • 2012-02-09
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多