【问题标题】:How to remove the last block of text between parentheses in a string, only if there are two blocks of text between parentheses at the end of string?仅当字符串末尾的括号之间有两个文本块时,如何删除字符串中括号之间的最后一个文本块?
【发布时间】:2021-09-25 14:05:17
【问题描述】:

我需要删除字符串中括号之间的最后一个文本块,但前提是该字符串末尾的括号之间有两个文本块。

例如,如果字符串是

Text (aaa) Text (bbb) Text (ccc) (ddd).

我需要得到

Text (aaa) Text (bbb) Text (ccc).

同时,如果字符串是

Text (aaa) Text (bbb) Text (ccc).

我需要保持原样。

我尝试了几个使用 https://regexr.com 的正则表达式(例如 /\s\(([^)]+)\)\s\(([^)]+)\)/),但没有一个适合我(我对正则表达式不是很有经验)。

你有什么建议吗?

【问题讨论】:

  • 如果有三个?最后总是有.吗?还是任何非单词字符?
  • 是的,我会给你一个建议:准确定义“文本块”的含义。

标签: javascript regex


【解决方案1】:

你可以使用

text = text.replace(/(\([^()]*\))\s*\([^()]*\)(?![\s\S]*\([^()]*\))/, '$1')
// Or, if there is always a dot and end of string (with possible trailing whitespace)
text = text.replace(/(\([^()]*\))\s*\([^()]*\)(?=\.\s*$)/, '$1')

请参阅regex demo详情

  • (\([^()]*\)) - 第 1 组 ($1):(,除 () 之外的零个或多个字符,然后是 ) 字符
  • \s* - 零个或多个空格
  • \([^()]*\) - (,除() 之外的零个或多个字符,然后是) 字符
  • (?![\s\S]*\([^()]*\)) - 负前瞻,确保在当前位置右侧的任何地方都没有其他 (...) 子字符串。
  • (?=\.\s*$) - 需要. 的正向前瞻,然后是零个或多个空格,然后是紧挨当前位置右侧的字符串结尾。

查看 JavaScript 演示:

const texts = ['Text (aaa) Text (bbb) Text (ccc) (ddd).','Text (aaa) Text (bbb) Text (ccc).'];
const rx = /(\([^()]*\))\s*\([^()]*\)(?![\s\S]*\([^()]*\))/;
for (const text of texts) {
    console.log(text, '=>', text.replace(rx, '$1'));
}

【讨论】:

  • 哇精彩的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 2016-10-16
  • 2021-05-13
  • 2017-12-03
  • 2017-05-26
  • 2018-04-19
相关资源
最近更新 更多