简体   繁体   English

如何通过使用python匹配特定的字符串

[英]how to match particular string by using python

I want to print the string. 我想打印字符串。 In my code i am not getting the right string. 在我的代码中,我没有得到正确的字符串。

line="\\python\001tag\file.txt"  
str=re.search(r"\[(0-9)+]",line)   (don't use raw_string here)

print str.group()

This gives nothing. 这什么也没有。 I want to extract 001 from there. 我想从那里提取001。

Note: I don't want to use rawstring.because here user is getting the path from other resource. 注意:我不想使用rawstring。因为这里用户正在从其他资源获取路径。 Is it possible to replace single slash by double slash to solve this problem 是否可以将双斜杠替换为单斜杠来解决此问题

You need to use a raw-string so that escape sequences are not processed: 您需要使用原始字符串,以便不处理转义序列:

sat = r"\\Python\001tag\file.txt"

Demo: 演示:

>>> sat = r"\\Python\001tag\file.txt"
>>> sat
'\\\\Python\\001tag\\file.txt'
>>> print(sat)
\\Python\001tag\file.txt
>>>

Three errors: '\\001' gives the codepoint in octal, actually the character at codepoint 1. Use double \\\\ or raw-strings. 三个错误: '\\001'以八进制形式给出代码点,实际上是代码点1处的字符。使用双\\\\或原始字符串。 Second: r'\\[' escapes the '[', use double \\\\ instead: r'\\\\[+0-9()]' (I have rearranged the characters in the set, so that it doesn't look like a expression group. Third: You want to look at str.group(0) to get the whole matched string. 第二个: r'\\['转义为'[',使用双\\\\代替: r'\\\\[+0-9()]' (我已经重新排列了集合中的字符,因此看起来不像第三:您想查看str.group(0)以获取整个匹配的字符串。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM