Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.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中的命名捕获组相结合?_Python_Regex - Fatal编程技术网

将两种模式与Python中的命名捕获组相结合?

将两种模式与Python中的命名捕获组相结合?,python,regex,Python,Regex,我有一个正则表达式,它使用before模式,如下所示: >>> RE_SID = re.compile(r'(?P<sid>(?<=sid:)([A-Za-z0-9]+))') >>> x = RE_SID.search('sid:I118uailfriedx151201005423521">>') >>> x.group('sid') 'I118uailfriedx151201005423521' >>RE_

我有一个正则表达式,它使用before模式,如下所示:

>>> RE_SID = re.compile(r'(?P<sid>(?<=sid:)([A-Za-z0-9]+))')
>>> x = RE_SID.search('sid:I118uailfriedx151201005423521">>')
>>> x.group('sid')
'I118uailfriedx151201005423521'

>>RE_SID=RE.compile(r')(?P(?

)不必调整正则表达式,只需删除字母数字和冒号以外的任何字符,即可使字符串更易于解析。然后,只需按冒号拆分,即可得到最后一项:

>>> import re
>>> 
>>> test_strings = ['sid:I118uailfriedx151201005423521">>', 'sid:<<"I118uailfriedx151201005423521']
>>> pattern = re.compile(r"[^A-Za-z0-9:]")
>>> for test_string in test_strings:
...     print(pattern.sub("", test_string).split(":")[-1])
... 
I118uailfriedx151201005423521
I118uailfriedx151201005423521
>>重新导入
>>> 

>>>test_strings=['sid:I118uailfriedx151201005423521“>>”,'sid:您可以使用单个正则表达式实现您想要的:

\bsid:\W*(?P<sid>\w+)

RE_SID=RE.compile(r'SID:(
RE_SID=RE.compile(r'SID:(@zolo)您的解决方案似乎有效。如果您愿意按照答案编写解决方案,我将非常感谢您的完整解释。特别是您代码的第一部分,我不确定我是否理解它?为什么第一部分没有
?p
。我真的更喜欢在我的模式之间使用“或”来使用我的解决方案rn,我有一个10000行的日志,我需要解析很多信息,我不确定你的解决方案是否适合我,@MaryamPashmi为什么你“不确定"。提供了提供的输入示例后,它就可以工作了,我认为解决方案非常简单。@MaryamPashmi但是,是的,如果您想对完整的日志文件运行
findall
,那么您可能应该使用一个正则表达式。谢谢。即使这些SID包含在较大的文本中,这种方法也可以工作。我真的想使用
>命名捕获组
,我希望以后能够引用它。我用命名捕获组进行了修改。有时日志包括
sid:
,中间有点。它是sid中唯一可以包含的非单词字符吗?使用
\bsid:\W*(?P\W+(?:\。\W+)*)
。如果你知道确切的尾随边界,你也可以将sid与
*?
@MaryamPashmi:This
(>
或只是
,在两者之间?我的解决方案会起作用,但这个不会。@zolo如果你能解释清楚,它会很完美。我在上面为你做了评论。我没有得到这部分
sid:(我看过
(?P.*))
style previous in other place(splunk)。该语句仅用于命名匹配的某个部分。这样,您可以依次使用多个变量,而无需将行的每一部分都放到不同的变量中。因此,如果要放置“sid:在变量定义的内部,您必须使用look-behind断言,这使得(在大多数语言中)不可能使用“*”+”之类的。将sid部分放出来看起来更容易,我甚至可以使用“?”。但是,我没有以任何方式更改/优化您的regexp。
>>> import re
>>> 
>>> test_strings = ['sid:I118uailfriedx151201005423521">>', 'sid:<<"I118uailfriedx151201005423521']
>>> pattern = re.compile(r"[^A-Za-z0-9:]")
>>> for test_string in test_strings:
...     print(pattern.sub("", test_string).split(":")[-1])
... 
I118uailfriedx151201005423521
I118uailfriedx151201005423521
\bsid:\W*(?P<sid>\w+)
import re
p = re.compile(r'\bsid:\W*(?P<sid>\w+)')
#test_str = "sid:I118uailfriedx151201005423521\">>" # => I118uailfriedx151201005423521
test_str = "sid:<<\"I118uailfriedx151201005423521" # => I118uailfriedx151201005423521
m = p.search(test_str)
if m:
    print(m.group("sid"))