首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的Python正则表达式不匹配查询字符串的一部分?

为什么我的Python正则表达式不匹配查询字符串的一部分?
EN

Stack Overflow用户
提问于 2019-06-10 00:26:19
回答 1查看 51关注 0票数 -1

我使用的是Python 3.7。我想提取url在查询字符串的"q=...&“部分之间的部分。我有这个代码

代码语言:javascript
复制
    href = span.a['href']
    print("href:" + href)
    matchObj = re.match( r'q=(.*?)\&', href, re.M|re.I)
    if matchObj:
        criteria = matchObj.group(1)

但是尽管我的href是这样的

代码语言:javascript
复制
href:/search?hl=en-US&q=bet+i+won+t+get+one+share&tbm=isch&tbs=simg:CAQSkwEJyapBtj9kKiIahwELEKjU2AQaAAwLELCMpwgaYgpgCAMSKMILxAufFcsLnBWeFZsVnRWABMcPsCKgLaMtoi2hLZ0tqziiI6w4uSQaMG01mL5LQ62s4q5ZMf-Wetz68lCkHfrFOOKs2CELzQJlPjHIMzmlp2Ny-a5t7hZbiCAEDAsQjq7-CBoKCggIARIEXLNODAw&sa=X&ved=0ahUKEwjThcCx59ziAhWKHLkGHfWjDs4Q2A4ILCgB

"matchObj“始终为NoneType,后面的行将不会被计算。我还需要做什么来修复我的正则表达式?

EN

回答 1

Stack Overflow用户

发布于 2019-06-10 00:34:14

在这里,我们将应用一个具有左边界和右边界的简单表达式,例如:

代码语言:javascript
复制
&q=(.+?)&

Demo

代码语言:javascript
复制
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"&q=(.+?)&"

test_str = "href:/search?hl=en-US&q=bet+i+won+t+get+one+share&tbm=isch&tbs=simg:CAQSkwEJyapBtj9kKiIahwELEKjU2AQaAAwLELCMpwgaYgpgCAMSKMILxAufFcsLnBWeFZsVnRWABMcPsCKgLaMtoi2hLZ0tqziiI6w4uSQaMG01mL5LQ62s4q5ZMf-Wetz68lCkHfrFOOKs2CELzQJlPjHIMzmlp2Ny-a5t7hZbiCAEDAsQjq7-CBoKCggIARIEXLNODAw&sa=X&ved=0ahUKEwjThcCx59ziAhWKHLkGHfWjDs4Q2A4ILCgB

"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx电路

jex.im可视化正则表达式:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56516345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档