0

I have been trying to split a string using regular expression in android without any success.

The string is formatted like this id;value| For example :

String valueString = "20;somevalue|4;anothervalue|10;athirdvalue|5;enoughwithvaluesalready";

I use this method to try o split the string.

public void splitString(String valueString){
    Pattern p = Pattern.compile("([\\d]+);([^\\|]+)");
    Matcher m = p.matcher(valueString);  
    boolean matches = m.matches();
}

When I run it in the Rubular-regex-editor it looks fine, in Android no matches are found. Any ideas?

4
  • to me, the error seems to be in escaping backshalshes. else regex ([\d]+);([^\\|]+) seems fine. Commented Sep 11, 2012 at 10:12
  • 1
    Why don't you use String.split instead of your own solution? Commented Sep 11, 2012 at 10:13
  • @KARASZIIstván I was just about to post that. Split on | followed by split on ; Commented Sep 11, 2012 at 10:14
  • @BunjiquoBianco I did the same, then I decided to ask it first :) Commented Sep 11, 2012 at 10:16

3 Answers 3

2

the method matches() tries to match the regex against the the complete string. And this does clearly not match.

find() will find the next matching substring.

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

Comments

2

Why don't you use String.split instead of writing your own solution?

Like:

final String[] entries = valueString.split("\\|");
for (String entry : entries) {
  final String[] fields = entry.split(";", 2);
}

2 Comments

I tried that but for some reason it split every character in the String. When I escaped it with \\| it worked fine :)
without the escaping it's looking for nothing or nothing (as split takes a regex argument), which weirdly matches everything.
0

I have tried your example, It will work only add .* at end of your Regx

    Log.i("MainActivity ", "Matches " + valueString.matches("([\\d]+);([^\\|]+).*"));

Above line return true

http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String)

Describe in above function

Comments

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.