我正在更改 javascript 中的字符串段并获得以下工作(第一次迭代 - 可选逗号)。
var foo = "wat:a,username:x,super:man"
foo.replace(/(username\:\w+)(?:,)*/,"go:home,");
//"wat:a,go:home,super:man"
现在的诀窍是我实际上可能只用键替换键/值...所以我需要用可选值 + 可选逗号捕获原始组。
var foo = "wat:a,username:,super:man"
foo.replace(/ ????? /,"go:home,");
//"wat:a,go:home,super:man"
作为奖励,我想要最简洁的方式来捕获可选数字/和字母(更新我的原件以也支持)
var foo = "wat:a,username:999,super:man"
foo.replace(/ ????? /,"go:home,");
//"wat:a,go:home,super:man"
最佳答案
您需要将 +
(前面的子模式出现 1 次或多次)量词替换为 *
(前面的子模式出现 0 次或多次)。
参见 Quantifier Cheatsheet at rexegg.com :
A+
One or moreA
s, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)
A*
Zero or moreA
s, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)
此外,您没有使用模式中定义的任何捕获组,因此我建议删除它们。
.replace(/username:\w*,*/,"go:home,")
^
如果您只有 1 个可选的 ,
,请仅使用 ?
量词(前面子模式的 1 次或 0 次重复):
.replace(/username:\w*,?/,"go:home,")
^
请注意,如果您可以在字符串或逗号结尾之前有任何字符,您还可以使用 Fede 的建议使用否定字符类:/username:[^,]*,*/
。 [^,]*
匹配逗号以外的任何字符(甚至是换行符)。
另外,请注意您不需要转义冒号。必须在字符类之外转义才能被视为文字的字符是 .
、*
、+
、?
, ^
, $
, {
, (
, )
, |
, [
, ]
, \
。参见 RegExp MDN reference .
关于javascript - 如何捕获带有可选数量的字母/数字后跟可选逗号的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530794/