Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

Java / Android regex question

1

40 views

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?

asked May 30, 2011 1:34 pm CDT
posted via StackOverflow

4 Answers

3
 

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));
    
    


answered May 30, 2011 2:23 pm CDT
2
 

Take a look at Pattern class.

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

answered May 30, 2011 2:23 pm CDT
0
 

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.

answered May 30, 2011 2:23 pm CDT
0
 
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
}

answered May 30, 2011 2:23 pm CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions