Regular expression to remove suffixes enclosed in square brackets from comma-delimited list
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 prob开发者_StackOverflow社区lem, I've a sample created here.
Can you help me to resolve this issue?
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
- Difference between
.*?
and.*
for regex - How can I exclude some characters from a class?
/\[(.+?)\]/g
This will enforce 1 or more characters inside the brackets. Also use parens to extract the match.
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
It is because your regular expression is greedy.
You need to modify the regex as [.*?]
You need to modify it as given here
精彩评论