Python Regex Match WillCard as the end of a word

98 views Asked by At

I'm trying to use regex to see if there's a word with a string that contains '*' and '*' can't be either the start of the word or in the middle of the word;

For example:

ip* -> match
ip*5p -> not match
*ip -> not match
this is ip* -> match
give me *ip not here -> not match

I tried the expression:

p = r'(?!\*).*\b\*'

But it failed in the case of "ip*5p", it thinks it as a match.

But if I add "end of word" which is '\b'

p = r'(?!\*).*\b\*\b'

It failed in all the cases as find nothing.

Also, I tried

p = r'(?!\*)\b.*\*'

But still not working properly. Any hint?

Note: Strings must have exactly one * symbol.

2

There are 2 answers

0
Avinash Raj On BEST ANSWER

You could use the below regex which uses positive lookahead assertion.

r'.*\S*\*(?=\s|$).*'

OR

r'.*?\*(?=\s|$).*'

DEMO

>>> import re
>>> s = """ip*
... ip*5p
... *ip
... this is ip*
... give me *ip not here"""
>>> for i in re.findall(r'.*\S*\*(?=\s|$).*', s):
...     print(i)
... 
ip*
this is ip*

\*(?=\s|$) POsitive lookahead asserts that the character following the symbol * must be a space character or end of the line anchor $.

0
AudioBubble On

You said that:

  1. You only want to match strings that have * at the end.

  2. There must be only one occurrence of * in the strings.

This means that Regex is overkill. All you need to do is count the number of * characters and then test if * is at the end of the string:

match = mystr.count('*') == 1 and mystr[-1] == '*'
# or
match = mystr.count('*') == 1 and mystr.endswith('*')

As you can see below, this works for all of your sample strings:

>>> mystr = 'ip*'
>>> mystr.count('*') == 1 and mystr[-1] == '*'
True
>>> mystr = 'ip*5p'
>>> mystr.count('*') == 1 and mystr[-1] == '*'
False
>>> mystr = '*ip'
>>> mystr.count('*') == 1 and mystr[-1] == '*'
False
>>> mystr = 'this is ip*'
>>> mystr.count('*') == 1 and mystr[-1] == '*'
True
>>> mystr = 'give me *ip not here'
>>> mystr.count('*') == 1 and mystr[-1] == '*'
False
>>>