1

I would like some thoughts on how to write a regular expression which validates a pattern

ex. .??2

one of more characters followed by two question marks followed by one or more numbers and if only if there is another repeating pattern then the seperator will be a semi colon.

more examples

--??9;.??50;,??3 - in this example I have the pattern repeating and that is why the semi colon

or

*??5 - a * followed by two qnestions marks followed by a number and no semi colon as there are no repeating groups

This is what i currently have

.+\?\?\d+(;|)+

1 Answer 1

1

The basic pattern is .+?\?\?\d+. We have made the first .+ non-greedy so it won't try to match the whole string right away. Use a repeated group to capture the subsequent patterns: r'(.+?\?\?\d+)(;.+?\?\?\d+)*'

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

4 Comments

import re num = ".??1000;" if re.search(r'(.+?\?\?\d+)(;.+?\?\?\d+)+',num): print "pass" else: print "fail" prints fail- but it should pass
Ha, good point. Fixed regex to use * instead of + on the repeated subsequence.
so you say this is correct r'(.+?\?\?\d+)(;.+?\?\?\d+)*' then num = ".??1000;." prints pass when it should fail
But that does pass...you're using re.search which doesn't try to match the whole string, so it matches just the first 7 characters. If you want to anchor at both ends, put ^ at the start and $ at the end.

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.