0

i have a problem with my python script, i want to make some regex function. Now i've done make it but how to detect if the string is matched with some patterns ?

I give an example, i have one string and two patterns of regex. Now how do i know if the string is matched with first pattern or second pattern ?

This is my script.

#!/usr/bin/python
import re
words = ["(@sosiora\*+([1-5]*)(\W|)+(@[a-z]*)(\W|))",
         "((@[a-z]*)(\W|)@sosiora\*+([1-5]*)+(\W|))"
        ]
pattern = re.compile('|'.join(words), flags=re.IGNORECASE)
text = "@sosiora*4 @samsungID"

m = pattern.findall(text)

print m;

if m:
    if len(m[0][1]) > 1:
        print 'Rating is not accepted : ' +m[0][1]
        print 'String: ' + text
    else :
        print 'Found %d matches' % len(m)
        print 'String: ' + text
        print 'Rating: ' + m[0][1]
        print 'Target: ' + m[0][3]
        print 'Pattern: ' // this is output to show the pattern
else:
    print 'rate is not found'

So, the output what i want is just Please help me, thank you.

1 Answer 1

2

You can loop over your patterns:

def _get_pos_and_group(s):
    words = ["(@sosiora\*+([1-5]*)(\W|)+(@[a-z]*)(\W|))",
             "((@[a-z]*)(\W|)@sosiora\*+([1-5]*)+(\W|))"
            ]

    for i, w in enumerate(words):
        if re.search(w, s):
            return i, re.search(w, s).group(0)
    return -1, None



print(_get_pos_and_group("@sosiora*4 @samsungID"))

(0, '@sosiora*4 @samsung')
Sign up to request clarification or add additional context in comments.

1 Comment

This also has the benefit of not combining 2 patterns that each are malformed, but when combined become something else - eg first pattern lacks a ) and second lacks a (

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.