Python正则表达式匹配字符串的最后一个单词

时间:2017-10-29 10:56:08

标签: python regex

我有以下字符串:

"crypto map OUTSIDEMAP 540 match address 3P-DC-CRYPTO"

而且,我试图仅与正则表达式匹配3P-DC-CRYPTO

到目前为止,我已设法编写以下正则表达式:

crypto_acl = re.findall("address [-\w+]*",output)

但是,它匹配address 3P-DC-CRYPTO

有什么建议吗?

5 个答案:

答案 0 :(得分:2)

您可以为positive lookbehind使用regex (?<=address\s)[-\w+]*

答案 1 :(得分:2)

实际上不需要正则表达式:

string = "crypto map OUTSIDEMAP 540 match address 3P-DC-CRYPTO"

# check for address as well
words = string.split()
if words[-2] == 'address':
    last_word = words[-1]
    print(last_word)

这将检查address,然后捕获最后一个单词。

答案 2 :(得分:1)

您可以通过捕获所需的单词来完成此操作:

>>> crypto_acl = re.findall("address ([-\w+]*)",output)
>>> crypto_acl
['3P-DC-CRYPTO']

此外,由于您在问题中提到需要字符串的最后一个单词,因此您可以这样做,而无需在address之后明确查找单词:

>>> crypto_acl = re.findall(r"\b([-\w+]+)$",output)
>>> crypto_acl
['3P-DC-CRYPTO']
#or simply 
>>> crypto_acl = output.split()[-1]
>>> crypto_acl
'3P-DC-CRYPTO'

现场演示here

答案 3 :(得分:0)

尝试使用正则表达式搜索,

import re

str = "crypto map OUTSIDEMAP 540 match address 3P-DC-CRYPTO"

result = re.search(r'(address .*)', str)

result.group()                          # return as 'address 3P-DC-CRYPTO'


result = re.search(r'address (.*)', str)

result.group()                     #  return as 'address 3P-DC-CRYPTO'
result.group(0)                   #  return as 'address 3P-DC-CRYPTO'
result.group(1)                  #  return as '3P-DC-CRYPTO'

答案 4 :(得分:0)

您可以使用Positive Lookbehind并捕获组():

import re
pattern=r"(?<=address )[\w-]+"
string_1="crypto map OUTSIDEMAP 540 match address 3P-DC-CRYPTO"
match=re.finditer(pattern,string_1,re.M)
for i in match:
    print(i.group())