tags:

views:

78

answers:

4

I need to format the followin string

name[Name], emloyeeno[Employee Number], joindate[Date Of Join:dd MMM yyyy], email[EMail]

as

name, employeeno, joindate, email

I'm trying to use a regular expression to resolve this, I best I could come up with is

/\[.*]/g

But it is not resolving the problem, I've a sample created here.

Can you help me to resolve this issue?

Thank you

+6  A: 

You can use negated character class. Something like [aeiou] matches exactly one of the lowercase vowels. [^aeiou] matches one of anything but.

For this problem, you can try /\[[^\]]*\]/g.

There are 3 parts:

  • \[ - a literal [
  • [^\]]* - zero-or-more repetition of anything but ]
  • \] - a literal ]

You may also try /\[.*?\]/ instead if you're lazy.

Related questions

polygenelubricants
Is there a specific reason to use /\[[^\]]*\]/g instead of /\[.*?\]/ as the first choice? Something like performance or the way in which the regular expression is resolved.
Arun P Johny
+3  A: 

It is because your regular expression is greedy.

You need to modify the regex as [.*?]

You need to modify it as given here

Arun P Johny
+3  A: 
/\[(.+?)\]/g

This will enforce 1 or more characters inside the brackets. Also use parens to extract the match.

bob.faist
+3  A: 

It is because your regular expression /[.*]/g is a greedy regular expression.

You regular expression matches all the characters between the first [ and the last ].

You need to change the regular expression as /[.*?]/g

Pradeep