-1

What is the regular expression to capture the following groups in the given string using JAVA:

hey,soul,345

with the constraint that the first word may include a comma as well. I have the following regex:

(.*),(.*),(.*)

but I essentially want to match the last 3 commas only.

Martin.
  • 10,494
  • 3
  • 42
  • 68
syker
  • 10,912
  • 16
  • 56
  • 68
  • @syker : assuming there is nothing more to your string than this, technically there is nothing wrong with your regex, it should match exactly what you are asking for...is there more to your string than this? – CrayonViolent May 15 '12 at 00:46

2 Answers2

3

I don't think you really need regex for this...if you have a single string with values separated by commas, and you only want the last 3 comma delimited values (meaning there's "three" values but first may have a comma in it), you can explode/split the string at the comma and have an array of the values. then just pop the last 2 array elements for #2 and #3 values, and implode/join whatever is left, for #1.

CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
1

You can add a $ to the end of the regex to match the last portion of the string, and then in each of the capturing groups, instead of matching a . (any character) you can match any non-comma character: [^,]. That should get you the last three comma-separated groups if you want to do it via regex. So your regex would be:

(.*),([^,]*),([^,]*)$
Ansari
  • 8,168
  • 2
  • 23
  • 34