Paresh Dudhat
Paresh Dudhat

Reputation: 1246

Why is my regex not parsed correctly on sms receiver in android?

In my android application I am parsing sms received through broadcast.

I put my regex in string.xml

<string name="message_verification_regex">^.*Your Verification Code is \\d{4}.*$</string>

And message I am trying to parse is

1234567890:
Your Verification Code is 5840.
Team ABC
-
Reply via way2sms.com. Now available on your mobile.

What is wrong with my regex?

Upvotes: 1

Views: 295

Answers (2)

nicolas
nicolas

Reputation: 3280

You can try to add (?m) at the start of your regex. That way, ^ will match the start of any line (instead of the start of your string, i.e. start of the 1st line only):

<string name="message_verification_regex">(?m)^.*Your Verification Code is \\d{4}.*$</string>

Upvotes: 1

Mofi
Mofi

Reputation: 49097

The string is a multiline string, but the dot does not match newline characters. Use

<string name="message_verification_regex">^[\\s\\S]*?Your Verification Code is \\d{4}[\\s\\S]*$</string>

The expression [\s\S] matches any whitespace character and any non-whitespace character which means really any character.

I must add that I don't know if escaping a backslash with an additional backslash is really necessary where the string with this regular expression is used. Therefore try also:

<string name="message_verification_regex">^[\s\S]*?Your Verification Code is \d{4}[\s\S]*$</string>

Upvotes: 1

Related Questions