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

时间:2017-04-20 13:19:15

标签: python regex

我必须写一个正则表达式引用一个字符串。我需要得到" $ u"之间的部分。和#34; $",我也需要匹配之前的部分" $ 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)

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

旁注 - ' \'在一个字符串中表示单个' \',因为它是特殊字符的开头。

无论如何,你可以让生活更轻松 - 如果你只保证一个" $ 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之前的内容。