2

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?

Brad Mace
  • 26,280
  • 15
  • 94
  • 141
Sambath
  • 23
  • 4

4 Answers4

4

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

Community
  • 1
  • 1
polygenelubricants
  • 348,637
  • 121
  • 546
  • 611
  • 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 Oct 16 '10 at 09:38
1
/\[(.+?)\]/g

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

bob.faist
  • 728
  • 7
  • 16
1

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

0

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
  • 365,836
  • 60
  • 503
  • 504