1

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...

4
  • 3
    “Some people, when faced with a problem think ‘I know; I use regular expressions’. Now they have two problems.” Commented 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? Commented 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 :) Commented Sep 22, 2012 at 11:41
  • Tim: Indeed. Still, the point holds in most cases :-) Commented Sep 22, 2012 at 13:31

3 Answers 3

4

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  "]
Sign up to request clarification or add additional context in comments.

Comments

2

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

You could use [^,]* instead of .+?, that would be a bit more efficient.
[^,] or .+? would not make any difference in assembly but you can choose what you want.
@Jan-StefanJanetzky I think Tim means the difference of performance.
it would only make a performance difference if there would be more than one char in [^]
No, that's not correct. Your regex, applied to the test string, takes the regex engine 49 steps until a match is achieved instead of 10 steps that my regex would take. By making the + 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.
2

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.