简体   繁体   中英

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

So far, I have managed to write the below regex :

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

However, it matches address 3P-DC-CRYPTO

Any suggestion?

您可以将 则表达式 (?<=address\\s)[-\\w+]*用于正则表达式

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.

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 :

>>> 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'

Live demo here

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():

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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