我知道(?<!)operator 背后的负面形象,但 Expo/React-Native 中使用的 Javascript 引擎似乎不支持它。我想要的是实现以下

export function processEmbedded(text: string): string {
  return text.replace(/(?<!!)\[Embedded\]/,javascript,regex,typescript,react-native,expo"/>
	














首页 > 解决方案 > 如何在不使用 `(?

我知道(?<!)operator 背后的负面形象,但 Expo/React-Native 中使用的 Javascript 引擎似乎不支持它。我想要的是实现以下

export function processEmbedded(text: string): string {
  return text.replace(/(?<!!)\[Embedded\]/

问题描述

我知道(?<!)operator 背后的负面形象,但 Expo/React-Native 中使用的 Javascript 引擎似乎不支持它。我想要的是实现以下

export function processEmbedded(text: string): string {
  return text.replace(/(?<!!)\[Embedded\]/gm, "![Embedded]");
}

我所做的有点笨拙,因为我剥离并重新添加了。

export function processEmbedded(text: string): string {
  return text
    .replace(/!\[Embedded\]/gm, "[Embedded]")
    .replace(/\[Embedded\]/gm, "![Embedded]");
}

对于我的情况,它确实有效,但我很确定在极端情况下它不起作用。


您可以使用捕获组来使用此变通解决方案:

export function processEmbedded(text: string): string {
  return text.replace(/(^|[^!])\[Embedded\]/gm, "$1![Embedded]");
}

正则表达式演示

(^|[^!])匹配行首或不在!第一个捕获组中的字符。在替换中,我们使用$1反向引用将其放回原处。

标签: javascriptregextypescriptreact-nativeexpo

解决方案


您可以使用捕获组来使用此变通解决方案:

export function processEmbedded(text: string): string {
  return text.replace(/(^|[^!])\[Embedded\]/gm, "$1![Embedded]");
}

正则表达式演示

(^|[^!])匹配行首或不在!第一个捕获组中的字符。在替换中,我们使用$1反向引用将其放回原处。


推荐阅读