aandroidtest
aandroidtest

Reputation: 1503

Android splitting string based on special characters

Currently I am trying to get an embedded URL from a RSS feed. Thus the initial URL has special characters like the following:

http://www.facebook.com/1.php?&...http://www.example.com...&"

I am using String.split(expression) function to split and get the http://www.example.com

But for special expressions like "?", I am not able to split the string.

Is there any other way to split strings based on special characters?

Upvotes: 1

Views: 4923

Answers (2)

BitParser
BitParser

Reputation: 3968

String.split expects a parameter which is a regular expression. Since ? is a special character in regular expressions, to do what you want, you'd actually write it as:

myStr.split("\\?");

And thus it recognizes it as the character ?, and not as a special regex character.

Note that two backslashes are needed. The regular expression itself is "\?", but since to put "\" in a java string we need to write it as "\\", the expression string thus becomes "\\?".

To learn more about regular expressions, I recommend you to check this site.

Upvotes: 7

Mark Allison
Mark Allison

Reputation: 21909

This is a uri and conforms to standard URI semantics. Therefore you can use one of the standard Uri representations in Android to do the heavy lifting for you. Your Uri contains a query string which follows the main part of the Uri after the ? character and is comprised of a number of key / value pairs separated by & characters. You simply need to parse your Uri in to an ndroid.net.Uri object and then call getQueryParameter(String paramName) to get your required query param:

String raw = "http://www.mydomain.com/index.html?param1=hello&param2=world&param3=test";
Uri uri = Uri.parse( raw );
String param = uri.getQueryParameter( "param2" );

This will return "world" in param.

Upvotes: 0

Related Questions