如何使用Python正则表达式提取引号内的值?及提取posted_data值返回None问题
解决Python正则提取posted_data对应值返回None的问题
我来帮你搞定这个问题!首先咱们得先搞清楚为什么你的正则会返回None——大概率是你的正则表达式没有精准匹配到目标内容的结构。
先看你提供的文本:
“I am trying to extract value of posted_data which is 2e54eba66f8f2881c8e78be8342428xd”
这里有几个需要注意的细节:
- 文本首尾是中文全角引号,如果你的正则用了半角引号
"去匹配,肯定抓不到目标范围 - 目标值
2e54eba66f8f2881c8e78be8342428xd是跟在posted_data which is之后的,正则需要准确定位这个衔接位置
下面给你两种可行的解决方案:
方案1:直接定位posted_data后的目标值
这种方法不需要纠结引号,直接抓取posted_data which is 后面的无空格字符串(你的目标值刚好是连续无空格的字符):
import re text = “I am trying to extract value of posted_data which is 2e54eba66f8f2881c8e78be8342428xd” # 正则匹配posted_data which is 后面的所有非空格字符,并捕获分组 match = re.search(r'posted_data which is (\S+)', text) if match: print(match.group(1)) # 输出: 2e54eba66f8f2881c8e78be8342428xd else: print("未匹配到目标内容")
方案2:先匹配中文引号范围再提取值
如果你需要严格限定在中文引号内的内容里提取,可以分两步操作:
import re text = “I am trying to extract value of posted_data which is 2e54eba66f8f2881c8e78be8342428xd” # 第一步:匹配中文引号包裹的全部内容 quote_match = re.search(r'“(.*?)”', text) if quote_match: inner_text = quote_match.group(1) # 第二步:从引号内的文本中提取posted_data对应值 value_match = re.search(r'posted_data which is (\S+)', inner_text) if value_match: print(value_match.group(1)) else: print("引号内未找到posted_data对应值") else: print("未找到中文引号包裹的内容")
为什么之前会返回None?
常见的几个坑:
- 用了半角引号
"去匹配文本里的全角引号“”,导致整个匹配范围失效 - 正则表达式的结构错误,比如没有正确衔接
posted_data和目标值之间的which is这段内容 - 没有考虑目标值的字符特征,比如用了错误的匹配规则(比如限定了字符长度或类型)
你可以试试上面的代码,应该能顺利提取到目标值啦!
内容的提问来源于stack exchange,提问作者elrich bachman




