简体   繁体   中英

RegEx to match words in comma delimited list

How can you match text that appears between delimiters, but not match the delimiters themselves?

Text

DoNotFindMe('DoNotFindMe')
DoNotFindMe(FindMe)
DoNotFindMe(FindMe,FindMe)
DoNotFindMe(FindMe,FindMe,FindMe)

Script

text = text.replace(/[\(,]([a-zA-Z]*)[,\)]/g, function(item) {
    return "'" + item + "'";
});

Expected Result

DoNotFindMe('DoNotFindMe')
DoNotFindMe('FindMe')
DoNotFindMe('FindMe','FindMe')
DoNotFindMe('FindMe','FindMe','FindMe')

https://regex101.com/r/tB1nE2/1

You can use:

var s = "DoNotFindMe('DoNotFindMe')\nDoNotFindMe(FindMe)\nDoNotFindMe(FindMe,FindMe)\nDoNotFindMe(FindMe,FindMe,FindMe)";
var r = s.replace(/(\([^)]+\))/g, function($0, $1) { 
       return $1.replace(/(\b[a-z]+(?=[,)]))/gi, "'$1'"); }, s);
DoNotFindMe('DoNotFindMe')
DoNotFindMe('FindMe')
DoNotFindMe('FindMe','FindMe')
DoNotFindMe('FindMe','FindMe','FindMe')

Here's a pretty simple way to do it:

([a-zA-Z]+)(?=,|\))

This looks for any word that is succeeded by either a comma or a close-parenthesis.

 var s = "DoNotFindMe('DoNotFindMe')\\nDoNotFindMe(FindMe)\\nDoNotFindMe(FindMe,FindMe)\\nDoNotFindMe(FindMe,FindMe,FindMe)"; var r = s.replace(/([a-zA-Z]+)(?=,|\\))/g, "'$1'" ); alert(r); 

Used the same test code as the other two answers; thanks!

Here's a solution that avoids the function argument. It's a bit wonky, but works. Basically, you explicitly match the left delimiter and include it in the replacement string via backreference so it won't get dropped, but then you have to use a positive look-ahead assertion for the right delimiter, because otherwise the match pointer would be moved ahead of the right delimiter for the next match, and so it then wouldn't be able to match that delimiter as the left delimiter of the following delimited word:

var s = "DoNotFindMe('DoNotFindMe')\nDoNotFindMe(FindMe)\nDoNotFindMe(FindMe,FindMe)\nDoNotFindMe(FindMe,FindMe,FindMe)";
var r = s.replace(/([,(])([a-zA-Z]*)(?=[,)])/g, "$1'$2'" );
alert(r);

results in

DoNotFindMe('DoNotFindMe')
DoNotFindMe('FindMe')
DoNotFindMe('FindMe','FindMe')
DoNotFindMe('FindMe','FindMe','FindMe')

(Thanks anubhava, I stole your code template, cause it was perfect for my testing! I gave you an upvote for it.)

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