忽略 HTML 实体的正则表达式

问题描述 投票:0回答:4

我需要 javascript 中的正则表达式来执行以下操作。

那些不属于 HTML 实体一部分的 a 实例应替换为 w

例如:

abc should change to wbc

aabacaa should change to wwbwcww

&abcaa& should change to &wbcww&  

等等。

我正在使用 JavaScript。

如有任何帮助,我们将不胜感激。

javascript regex
4个回答
6
投票

试试这个:

"&abcaa&".replace(/&[^;]+;|a/g, function($0) {
    return $0 === "a" ? "w" : $0;
})

0
投票

一种非正则表达式的方式,用你最喜欢的编程语言,在“&a”(或

&
)上分割你的字符串,替换分割的项目,然后加入回来,例如在Python中

>>> s="&abcaa&"
>>> '&a'.join( [ i.replace("a","w") for i in  s.split("&a") ] )
'&wbcww&'

0
投票

这是我想出的一个 JS 函数解决方案,它更加灵活/可重用,并且可以在 OP 示例的范围之外工作,将

"a"
s 替换为
"w"
s:

/**
 * Replaces specified characters in a string, ignoring any characters that
 * are part of HTML entities.
 *
 * @param {string} text
 * @param {string} replace1 - What you want replaced
 * @param {string} replace2 - What will be the replacement
 * @returns {string} - The modified string with replacements
 */
const replaceIgnoringHtmlEntities = (text, replace1, replace2) => {
  const htmlEntityRegex = /(&.+;)(.*?)(\1)/gi;

  // Split the text by HTML entities
  const parts = text.split(htmlEntityRegex);

  const replacedParts = parts.map((item) => {
    // If it's an HTML entity, return it unchanged
    const isHTMLEntity = /(&.+;)(.*?)/g.test(item);
    if (isHTMLEntity) return item;

    const replaceRegex = new RegExp(replace1, "g");
    return item.replace(replaceRegex, replace2);
  });

  return replacedParts.join("");
};

// Example usage
// Output: "wbc"
console.log(replaceIgnoringHtmlEntities("abc", "a", "w"));

// Output: "wwbwcww"
console.log(replaceIgnoringHtmlEntities("aabacaa", "a", "w"));

// Output: "&wbcww&"
console.log(replaceIgnoringHtmlEntities("&abcaa&", "a", "w"));

// Output: "`TEST_HELLO_THIS`"
console.log(replaceIgnoringHtmlEntities("`TEST_60_THIS`", "60", "HELLO"));

-1
投票

作为更一般的答案,在编写正则表达式时,我做的第一件事是访问 http://rubular.com 并布置几个测试字符串。然后,我编写并重新处理正则表达式,直到它满足我的需要。

是的,我知道 Rubular 是一个 Ruby 正则表达式站点,但 RegExp 语法非常相似,即使对于大多数语言来说不完全相同(我认为 Perl 使用扩展语法)。我已经成功使用 Rubular 来测试 Java RegExps。

© www.soinside.com 2019 - 2024. All rights reserved.