1

I would like to create a regex in Java / Android which truncates a string after, or actually at, the third comma. Is this possible? Any suggestions to get me started on this?

2
  • 2
    Suggestions to get you started on this? Learn regular expressions. Commented May 30, 2011 at 18:36
  • @Martihno - I know...I know. I just do them infrequently enough that I always kind of start from scratch. Posting a question on SO gives me a bit of motivation to get going on it. Commented May 30, 2011 at 19:05

4 Answers 4

4

Not sure regular expressions would be my first approach here. Below are my alternatives anyway.

  • Using regular expressions (ideone.com demo)

    Matcher m = Pattern.compile("(.*?,.*?,.*?),").matcher(str);
    if (m.find())
        str = m.group(1);
    


  • Using indexOf / substring (ideone.com demo)

    str = str.substring(0, str.indexOf(',',
                           str.indexOf(',',
                           str.indexOf(',') + 1) + 1));
    


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

Comments

3

Take a look at Pattern class.

Alternatives: String#split your string or use a StringTokenizer.

4 Comments

Using split or StringTokenizer would force him to concatenate the results. Not very elegant imo.
Sure, but I don't know what he actually wants to achieve or do with the result (thus only 'alternatives'). Just wanted give some suggestions as stated in his answer ;)
Thanks for the idea. All the answers were great, but since regular expressions look like swears to me, I went with a nice little split and a loop. .
Did you look at my two non-regex solutions? They don't require any loops.
1

Translate s/([^,]*,){3}.+/\1/ into Java regex-ese to truncate after the third comma, s/([^,]*,[^,]*,[^,]*),.+/\1/ to have the truncated portion include the third comma.

Comments

1
int comma = -1;
int n = 0;
do {
    comma = str.indexOf(',', comma + 1);
} while (comma >= 0 && ++n < 3);
if (comma > 0) {
    str = str.substring(0, comma);
} else {
    // third comma not found
}

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.