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?
-
2Suggestions to get you started on this? Learn regular expressions.R. Martinho Fernandes– R. Martinho Fernandes2011-05-30 18:36:08 +00:00Commented 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.Jack BeNimble– Jack BeNimble2011-05-30 19:05:42 +00:00Commented May 30, 2011 at 19:05
Add a comment
|
4 Answers
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));
Comments
Take a look at Pattern class.
Alternatives: String#split your string or use a StringTokenizer.
4 Comments
aioobe
Using split or StringTokenizer would force him to concatenate the results. Not very elegant imo.
dertkw
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 ;)
Jack BeNimble
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. .
aioobe
Did you look at my two non-regex solutions? They don't require any loops.