(=字符串)的正则表达式

2024-06-16 09:54:43 发布

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

我有一个包含数千行的文本文件。下面是一个例子

line = .Falies/367. 11DG1550/11DG15537.Axiom=nt60
line = .Failies/367. 11DG1550/11DG15537.Axiom=nt50

我试图提取“nt60”、“nt50”结尾的字符串。你知道吗

lines = line.split('=')
version = lines[-1]

问题是将包含行尾字符('\n'

我考虑使用正则表达式搜索来匹配从('=nt')开始的字符串 但是我不知道应该用什么来匹配=, word, number。你知道吗

有人能帮忙吗?你知道吗


Tags: 字符串version结尾line字符例子splitlines
2条回答

你的第一个方法绝对是好的。您只需使用使用第一个方法提取的字符串,然后对其应用strip()

strip()从字符串中删除所有前导空格和尾随空格以及换行符。你知道吗

>>> your_str = 'nt60\n'
>>> your_str.strip()
'nt60'

对于您的情况:

lines = line.rsplit('=',1)
version = lines[-1].strip()

匹配=ntnumber的正则表达式是:

=(nt\d+)

在你的例子中:

line = .Falies/367. 11DG1550/11DG15537.Axiom=nt60 
line = .Failies/367. 11DG1550/11DG15537.Axiom=nt50 

它将返回两个匹配项:

MATCH 1
1.  [49-53] `nt60`
MATCH 2
1.  [105-109] `nt50`

说明:

`=` matches the character `=` literally 
1st Capturing group `(nt\d+)`
   `nt` matches the characters `nt` literally (case sensitive)  
   `\d` match a digit `[0-9]`  
   `+` Quantifier: Between one and unlimited times, as many times as possible,  
       giving back as needed  

如果您希望正则表达式匹配a=wordnumber,那么只需将nt替换为\w+即可匹配任何单词。你知道吗

希望这有帮助。你知道吗

相关问题 更多 >