【问题标题】:JavaScript Regex match only if character occurs only ones followed by alphanumeric characterJavaScript 正则表达式仅在字符仅出现时才匹配,后跟字母数字字符
【发布时间】:2018-10-18 04:48:21
【问题描述】:

我想要一个与字符 & 匹配的 JavaScript 正则表达式,前提是它恰好出现一次,后跟一个字母数字字符。

例子:

  • &De&&let&&&e A&ll → 应该只匹配 &D&l
  • Hum&&an&s → 应该只匹配 &s

这是我想出的,但不太正确:

(?:[^\&]|^)\&([a-zA-Z0-9])

var strings = `&De&&let&&&e A&ll
 Hum&&an&s`

console.log(
  strings.match(/(?:[^\&]|^)\&([a-zA-Z0-9])/g)
)

【问题讨论】:

  • 最终目标是什么? Replace the matches with something else? 你的正则表达式看起来很好,你可以把 ([a-zA-Z0-9]) 变成 (?=[a-zA-Z0-9]) 前瞻。
  • 我给你做了一个sn-p。请更新预期的输出应该是什么
  • 你的代码没问题。您只需将第一个组添加到捕获组,然后在调用 replace 方法时将它们包含在内。
  • 是的,$1 是存储在组 1 中的值的替换反向引用(或占位符)。

标签: javascript regex typescript


【解决方案1】:

您可以将第一组转换为capturing group,以便您可以使用$1 占位符(也称为replacement backreference)恢复替换字符串中的值。类似地,您可以将捕获的字母数字字符恢复到另一个组中。

以下是在您定义的上下文中将& 替换为# 的示例:

var strs = ['&De&&let&&&e A&ll', 'Hum&&an&s'];
var rx = /(^|[^&])&([A-Z0-9])/gi;
for (var s of strs) {
	console.log(s.replace(rx, "$1#$2"));
}

【讨论】:

    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多