1

Trying to write a Regex expression in Python to match strings.

I want to match input that starts as first, first?21313 but not first.

So basically, I don't want to match to anything that has . the period character.

I've tried word.startswith(('first[^.]?+')) but that doesn't work. I've also tried word.startswith(('first.?+')) but that hasn't worked either. Pretty stumped here

2
  • Don't make [^.] optional with ?. Commented May 8, 2015 at 23:35
  • str.startswith() takes literals - not regular expressions... look into importing and using the actual re and its .match method... Commented May 8, 2015 at 23:36

2 Answers 2

1
 import re  
 def check(word):
        regexp = re.compile('^first([^\..])+$')
        return regexp.match(word)

And if you dont want the dot: ^first([^..])+$ (first + allcharacter except dot and first cant be alone).

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

2 Comments

How do I do this with startswith? When I tried, it gave me issues?
why do you want do it with startswith?, if you have a lot of checks and you want do it in only one line, you can create method like: check(word,regexpParam) and re.compile(refexpParam) and you change: word.startswith(('first[^.]?+')) for check(word,'^first([^\..])+$')
0

You really don't need regex for this at all.

word.startswith('first') and word.find('.') == -1

But if you really want to take the regex route:

>>> import re
>>> re.match(r'first[^.]*$', 'first')
<_sre.SRE_Match object; span=(0, 5), match='first'>
>>> re.match(r'first[^.]*$', 'first.') is None
True

2 Comments

There are a lot of edge cases and allowable values, first.stuffafter being one. So that definitely won't work EDIT: didn't see your edit in time. Looks like the other answer and I'll try testing
@simplycoding What output are you expecting from first.stuffafter? Do you expect a list in the form of ['first', 'stuffafter']? Do you expect two capture groups from the match that contains the text?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.