简体   繁体   中英

regex - match exact text within square brackets

I want to convert "categories": ["Doctors", "Health & Medical"],

to "categories": ["Doctors, Health & Medical"],

In otherwords, I want to find " ," (with space in the middle of open qoute and comma).

then replace with ,

However, " ," repeats elsewhere in the document therefore using " ," alone won't be enough. The best best is to say find " ," within [...]

For example: "categories": ["Doctors", "Health & Medical"], "city": "Phoenix", "count": 9

Thank you very much in advance

As pointed out in the comments, you should avoid regex if you can.

It is pretty trivial to achieve something like this in JavaScript with a single line.

For instance, you could just use the .join() method:

obj.categories = [obj.categories.join(', ')];

Example Here


However, if you don't have a choice, you can use the following:

/((?:\[[^\]]*?)|(?:(?<!^)\G[^\]]*?))(?:", ")(?=[^\]]*"\])/g

Then replace the matches with \\1, .

Example Here

Based on your test cases, the string:

"categories": ["Doctors", "Health", "Other"], "city": "Phoenix", "count": 9

would output:

"categories": ["Doctors, Health, Other"], "city": "Phoenix", "count": 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM