简体   繁体   English

如何仅匹配特定字符的正则表达式模式

[英]How to match regex pattern only up to certain character

line =abcsdfs?a=name&ab=fsdfsd&c=sfssf
pattern = '\?a=(.+?)&'
match_pattern = re.search(pattern, line)

I get result as ?a=name& and and match_pattern.group(1) as name我得到的结果是?a=name&match_pattern.group(1)作为name

But if I remove word name I don't get NONE return?但是如果我删除单词名称,我不会得到 NONE 回报?

line =abcsdfs?a=&ab=fsdfsd&c=sfssf
pattern = '\?a=(.+?)&'
match_pattern = re.search(pattern, line)

I get result as ?a=&ab=fsdfsd& and match_pattern.group(1) as &ab=fsdfsd我得到的结果是?a=&ab=fsdfsd&match_pattern.group(1)&ab=fsdfsd

How can I stop it to go further.我怎么能阻止它走得更远。 I mean how to get result None/ error if do match_pattern.group(1)我的意思是如果执行match_pattern.group(1)如何获得结果无/错误

Try this instead:试试这个:

pattern = '\?a=(.*?)&'

Note that .+?请注意.+? matches 1 or more characters;匹配1 个或多个字符; .*? matches 0 or more characters.匹配0 个或多个字符。

Of course, if what you are trying to do is to match URL query strings, regex is the wrong tool.当然,如果您要做的是匹配 URL 查询字符串,那么 regex 是错误的工具。 Try the urlparse module:试试urlparse模块:

import urlparse
url = 'abcsdfs?a=name&b=&ab=fsdfsd&c=sfssf'
url = urlparse.urlsplit(url)
qs = url.query
qs = urlparse.parse_qs(qs, keep_blank_values=True)
print [qs['a'][0], qs['b'][0], qs['c'][0]]

您应该匹配除“&”之外的所有符号:

pattern = '\?a=([^&]*)'

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

相关问题 如何使Python正则表达式模式在开头或某个字符串的开头匹配某个字符? - How to make a Python regex pattern match a certain character at the start, or just be the start of the string? 正则表达式仅在行不以字符开头时才匹配模式 - Regex to match pattern only if the line does not start with a character 正则表达式:如何匹配两个字符但排除某个组合 - Regex: How to match two character but exclude a certain combination 如何仅在检测到特定正则表达式模式的情况下使用 re.sub 对字符串中的数据进行重新排序,而在其他情况下则不然 - How to reorder data from a character string with re.sub only in cases where it detects a certain regex pattern,amd not in other cases 正则表达式匹配字符串模式中的某些字符 - Regex matching certain character in string pattern 正则表达式模式以匹配未被特殊字符包围的字符 - Regex Pattern to Match Character Not Surrounded by Particular Characters 正则表达式以使用Python匹配某些句子模式 - Regex to match certain sentence pattern with Python 使用正则表达式匹配直到某个模式 - match until a certain pattern using regex 与某些扩展名不匹配的正则表达式模式? - Regex pattern that does not match certain extensions? 正则表达式匹配某个字符后的单词 - regex match a word after a certain character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM