1

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?

1
  • If you want to match the last word, you don't have to use regex: output.split()[-1] will do that. Commented Oct 29, 2017 at 10:57

5 Answers 5

2

You can use a positive lookbehind (?<=address\s)[-\w+]* for your regex.

Sign up to request clarification or add additional context in comments.

1 Comment

Since I have more than 1 line to be checked, your option is the right one for me. Thanks
2

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.

Comments

1

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

Comments

0

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'

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.