[英]Python regex match last word of a string
I have the following string: 我有以下字符串:
"crypto map OUTSIDEMAP 540 match address 3P-DC-CRYPTO"
And, I am trying to match with a regex only 3P-DC-CRYPTO
而且,我正在尝试仅使用正则表达式3P-DC-CRYPTO
So far, I have managed to write the below regex : 到目前为止,我已经设法编写了以下正则表达式:
crypto_acl = re.findall("address [-\w+]*",output)
However, it matches address 3P-DC-CRYPTO
但是,它匹配address 3P-DC-CRYPTO
Any suggestion? 有什么建议吗?
No regex needed, actually: 实际上不需要正则表达式:
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)
This checks for address
and then captures the last word. 这将检查address
,然后捕获最后一个单词。
You can do it by capturing the desired word like this: 您可以通过捕获所需的单词来做到这一点,如下所示:
>>> crypto_acl = re.findall("address ([-\w+]*)",output)
>>> crypto_acl
['3P-DC-CRYPTO']
Also, since you've mentioned in the question that you need the last word of a string, you can simply do it like this, without explicitly looking for the word after address
: 另外,由于您在问题中提到需要字符串的最后一个单词,因此您可以像这样简单地完成操作,而无需在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'
Try with regex search, 尝试使用正则表达式搜索,
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'
You can use Positive Lookbehind and capture the group(): 您可以使用正向后看并捕获group():
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.