jennymo
jennymo

Reputation: 1480

Android Studio: Regex not working

I migrated my project from Eclipse to Android Studio and everything worked fine. In this project I have a Regex which should find all image urls in a json-object I get from an API.

This is the Regex I have:

Pattern pattern = Pattern.compile("https?:\\/\\/[^\"]*?\\.(png|jpe?g|img)");

            Matcher matcher = pattern.matcher(obj.toString());
            while(matcher.find()) {
                ImageBackgroundFetcher.getInstance(mActivity).addImageToLoadingQueue(matcher.group());
            }

obj is the JSONObject I have with the image urls. It looks like the following and I would like to extract the url of the image (the bold marked part) {"image":"http:\/\/www.test.de\/media\/2015\/01\/16\/bildtitel.jpg"}

After I migrate the project from Eclipse to Android Studio this Regex isn't working any longer. The matcher.find()-Method did not return true and Android Studio gives me a warning in the code at the regex part "\\/\\/" where it says "redundant character escape"

I already googled but didn't find a solution. Any ideas how to solve the problem would be great, thanks in advance ;)

Upvotes: 4

Views: 8883

Answers (5)

I was Using the static method Regex.fromLiteral() and it did not work as expected. After a lot of effort I found that this method does not recognize the escaped characters and treats the provided string as such.

This is my regular expression: ([a-zA-Z0-9.-]+)\.([a-zA-Z.-]+)(\/\S*)? and it is in it's original form. without escapes.

Honestly I couldn't make it work using that method so I just ended up using this approach:

val pattern = Regex("""([a-zA-Z0-9.-]+)\.([a-zA-Z.-]+)(\/\S*)?""")
    return pattern.matches(text)

As you can see I provided my regex inside a string inside 3 quotation marks. It is the Kotlin way to say that i don't want any escaping inside this string and it is a Literal.

Upvotes: 0

tricknology
tricknology

Reputation: 1138

It has to do with the way Java treats Regex, it needs String literals. So \\ for a single \

Upvotes: 0

Fantasy Fang
Fantasy Fang

Reputation: 6166

You can use AS function to check Regex.

Press Shortcut: Alt+Enter → check regexp enter image description here

Match result]

enter image description here

Upvotes: 16

N Dorigatti
N Dorigatti

Reputation: 3540

I usually use this site to check:

http://regexr.com/

using the pattern:

(https?:\\/\\/.+(png|jpe?g|img))(?:")

and capturing the first group it should work. Just check in java, escaping \ and / is not the same as the site i linked

Using your expression, the pattern:

https?:\/\/[^\\"]*?\\.(png|jpe?g|img)

should work too. This last string should not be escaped again. Check also your string in the original eclipse project!

Upvotes: 0

jennymo
jennymo

Reputation: 1480

Okay, I am able to solve this issue. The correct regex is:

https?:\\\\/\\\\/[^\"]*?\\.(png|jpe?g|img)

Upvotes: 3

Related Questions