如何使用正则表达式来匹配包含两个反斜杠的字符串

2024-10-03 11:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须写一个引用字符串的正则表达式。我需要得到“$u”和最后一个“$”之间的部分,还需要匹配“$u”之前的部分 现在我写了如下正则表达式,但它不能工作

a='=856  \\$uhttp://sfx-852cuh.hosted$'
#Two backslash may replace by other characters:a='=856  aa$uhttp://sfx-852cuh.hosted$'
result=re.search('=\w{3}\s{2}\S{2}\$u(.*)\$', a)
target_str=result.group(1)

Tags: 字符串researchbyresultreplacemayaa
2条回答

字符串中的旁注-“\”表示单个“\”,因为它是特殊字符的开头。你知道吗

无论如何,你可以让生活更轻松-如果你只保证一个“$u”:

a='=856  \\$uhttp://sfx-852cuh.hosted$'
#Two backslash may replace by other characters:a='=856  aa$uhttp://sfx-852cuh.hosted$'
result=re.search('(.*)\$u(.*)\$', a)
NOT_str=result.group(2)

组1包含$u之前的内容。你知道吗

如果在$u之前需要1或2个非空白字符,并且不使用具有str名称的变量,请将\S{2}替换为\S{1,2}

import re
a='=856  \\$uhttp://sfx-852cuh.hosted$'
result=re.search(r'=\w{3}\s{2}\S{1,2}\$u(.*)\$', a)
expected_value = ''
if result:
    expected_value = result.group(1)
print(expected_value)   

参见Python demo

相关问题 更多 >