簡體   English   中英

正則表達式無法找到並替換包含括號的字符串

[英]Regex is unable to find and replace a string containing parentheses

我試圖在段落中找到一個句子(包含在文本區域中),並突出顯示它。 如果句子不包含左括號和右括號,則一切正常,例如下面的示例。 replace 方法無法用“mark”標簽包圍的等效字符串替換字符串。 誰能建議我如何更新正則表達式以查找和替換包含括號的字符串? 我是否需要先找到所有括號並將其替換為“/(”和“/)”?

const text = "An economy is composed of suppliers (workers) and demanders (firms)."

const regex = new RegExp(text, "\d");
// regex returns: /The market for labor, then, is composed of suppliers (workers) and demanders (firms). /
        console.log("REGEX:", regex);
        let match = text.replace(regex, "<mark>$&</mark>");
        console.log("MATCH:", match);

突出顯示括號中的文本

html:

<html>
  <body>
   <p id="txt">"(An economy is composed of suppliers (workers) and demanders (firms).)</p>
  </body>
</html>

記者:

function hilitetext() {
  const s = document.getElementById("txt").textContent;
  const regex = /(?:^[^(]?[^(]+)?(\(\w+\))/g;//retains parenthesis
  //const regex = /(?:^[^(]?[^(]+)?\((\w+)\)/g;//removes parenthesis
  document.getElementById("txt").textContent = s.replace(regex, "<mark>$1</mark>");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM