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
Active
Viewed 278 times
1
-
2Suggestions to get you started on this? [Learn regular expressions](http://www.regular-expressions.info/). – R. Martinho Fernandes May 30 '11 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. – Jack BeNimble May 30 '11 at 19:05
4 Answers
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));
Using
nthOccurrence
(ideone.com demo)str = str.substring(0, nthOccurrence(str, ',', 2));
3
Take a look at Pattern
class.
Alternatives: String#split
your string or use a StringTokenizer
.

dertkw
- 7,798
- 5
- 37
- 45
-
Using split or StringTokenizer would force him to concatenate the results. Not very elegant imo. – aioobe May 30 '11 at 18:51
-
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 ;) – dertkw May 30 '11 at 18:53
-
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. . – Jack BeNimble May 30 '11 at 19:40
-
Did you look at my two non-regex solutions? They don't require any loops. – aioobe May 30 '11 at 19:44
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.

Jeremy W. Sherman
- 35,901
- 5
- 77
- 111
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
}

Ted Hopp
- 232,168
- 48
- 399
- 521