I have the following string in javascript,
Id:121,RefId:123,Date:Sep 22, 2012 12:00:00 AM
when i tried to split it into 3 key,value pairs using , as the separator it is giving me wrong out put because in date there is another ,(comma).
So i guess i must use regular expression.
I want to display it as follows;
Id:121
RefId:123
Date:Sep 22, 2012 12:00:00 AM
Can anyone please suggest how to overcome the extra comma in date using regular expression?
Thanks in Advance...
-
3"Some people, when faced with a problem think ‘I know; I use regular expressions’. Now they have two problems."Joey– Joey2012年09月22日 11:29:23 +00:00Commented Sep 22, 2012 at 11:29
-
How did you got such a string? Its ambiguous format is not easy to handle. Why don't you use JSON, CSV or such?Bergi– Bergi2012年09月22日 11:41:02 +00:00Commented Sep 22, 2012 at 11:41
-
1@Joey: As both our failed attempts to do it without regexes show, sometimes not using a regex causes more problems :)Tim Pietzcker– Tim Pietzcker2012年09月22日 11:41:15 +00:00Commented Sep 22, 2012 at 11:41
-
Tim: Indeed. Still, the point holds in most cases :-)Joey– Joey2012年09月22日 13:31:46 +00:00Commented Sep 22, 2012 at 13:31
3 Answers 3
You mean split on the , which is followed not the white space?
'Id:121,RefId:123,Date:Sep 22, 2012 12:00:00 AM '.split(/,(?=\S)/);
// will give you ["Id:121", "RefId:123", "Date:Sep 22, 2012 12:00:00 AM "]
Comments
if you really want a regular expression (instead of a limited split) you could do this:
var text = "Id:121,RefId:123,Date:Sep 22, 2012 12:00:00 AM";
text.match(/^(.+?),(.+?),(.+)$/);
5 Comments
[^,]* instead of .+?, that would be a bit more efficient.+ quantifier lazy, you force the regex engine to backtrack after each character. This is even worse if the input string cannot be matched. If I take out the second and third comma from the string, your regex takes 248 steps to figure out a non-match, mine takes 8.If you would like to use a regular expression, you can try this:
re = /^Id:(\d+),RefId:(\d+),Date:(.+)/
matches = re.exec("Id:121,RefId:123,Date:Sep 22, 2012 12:00:00 AM")
matches[1] // "121"
matches[2] // "123"
matches[3] // "Sep 22, 2012 12:00:00 AM"