Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在python中使用正则表达式获取值_Python 3.x_Regex - Fatal编程技术网

Python 3.x 如何在python中使用正则表达式获取值

Python 3.x 如何在python中使用正则表达式获取值,python-3.x,regex,Python 3.x,Regex,这是我的示例代码 import re string = '[P-123,SHA-123]' pattern = re.compile(r"^\[(?P<curve>).*\]$", re.MULTILINE | re.IGNORECASE) result = pattern.search(string) print(result) 预期产出: P-123您可以尝试使用这个正则表达式\W[A-Z]-[0-9]*提取大写字母,然后是数字 import re st

这是我的示例代码

import re

string = '[P-123,SHA-123]'
pattern = re.compile(r"^\[(?P<curve>).*\]$", re.MULTILINE | re.IGNORECASE)
result = pattern.search(string)
print(result)
预期产出: P-123

您可以尝试使用这个正则表达式\W[A-Z]-[0-9]*提取大写字母,然后是数字

import re

string = '[P-123,SHA-123]'
pattern = re.compile(r"\W([A-Z]-[0-9]*)", re.MULTILINE | re.IGNORECASE)
result = pattern.search(string).group(1)
print(result)
输出

P-123

如果要匹配该数据格式,请执行以下操作:

^\[(?P<curve>[A-Z]-\d+),[A-Z]+-\d+]\Z
输出

P-123

你面临什么问题?请也提一下。这将有助于社区为您提供帮助。如果您希望,任何数字组合之前都只能有p;您可以使用?ip-\d+为什么希望输出?您的正则表达式特别指出要通过右方括号和字符串的末尾匹配所有内容
import re

string = '[P-123,SHA-123]'
pattern = re.compile(r"\[(?P<curve>[A-Z]-\d+),[A-Z]+-\d+]\Z", re.MULTILINE | re.IGNORECASE)
result = pattern.match(string)
print(result.group("curve"))
P-123