简体   繁体   中英

find first matches character in regular expression

i have a string that i want to find "a" character and first "c" character and replace with "*" character, but regular expression find all "a" and "c" character i don't know how do it.

here my code:

var pattern=/[a][c]/g; //here my pattern
var str1="aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc";
var rep=str1.replace(pattern,"*");
$("p").html(rep);

You need two replacements, because a single one replaces either a or c , depending on the first occurence in the string.

 var string = "aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc", result = string.replace(/a/, '*').replace(/c/, '*'); console.log(result);

An approach with a single replace and a closure over a hash table.

 var string = "aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc", result = string.replace(/[ac]/g, (h => c => h[c]? c: (h[c] = '*'))({})); console.log(result);

I guess [ac] might simply suffice:

 const regex = /[ac]/g; const str = `aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc`; const subst = `*`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log(result);


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com . If you'd like, you can also watch in this link , how it would match against some sample inputs.


You can use capture groups for all a or c sequences but the 1st, and replace them with '*$1' ($1 is the replacement pattern for the capture group):

 const str = `aaaaaaaaaabbbbbbaaaaaaaaaabbbccccccccccbbbbbbbbccc`; const result = str.replace(/[ac]([ac]+)/g, '*$1'); console.log(result);

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