【问题标题】:Remove text inside parentheses at the end of the string删除字符串末尾括号内的文本
【发布时间】:2016-06-17 10:25:52
【问题描述】:

我想要一个正则表达式,它可以找到括号中存在的字符串并将其删除,就像我希望执行此操作的示例字符串一样:

09373 837 937 (mobile) // Output should be "09373 837 937"
9838373838 (home) // Output should be "9838373838"
+19383947388 (home) // Output should be "+19383947388"
(938)3947388 (mobile) // Output should be "(938)3947388"

所以第一部分总是联系一个可以是任何格式的号码,最后一部分总是标签,我想删除那个标签

【问题讨论】:

  • String.replace(/\s*\(.*?$/, '')
  • 你需要.replace(/\s*\([^()]*\)$/, '').replace(/\s*\([^)]*\)\s*$/, '')甚至.replace(/[^\S\r\n]*\([^)]*\)\s*$/, '')
  • @WiktorStribiżew 谢谢这个工作,你能把它发布到答案中以便我接受它
  • 除非您描述您尝试过的内容,否则我最好将其保留在评论中。
  • 第一个我尝试过并且有效的方法:.replace(/\s*([^()]*)$/, '')

标签: javascript regex


【解决方案1】:

你可以使用

.replace(/\s*\([^()]*\)$/, '')

请参阅regex demo

如果您需要确保只删除 horizo​​natal 空格*,请将 \s* 替换为 [^\S\r\n]*

模式说明

  • \s* - 零个或多个空格(替换为[^\S\r\n] 以匹配水平空格,即\s\r\n“减去”)
  • \( - 文字 ( 符号
  • [^()]* - 除() 之外的零个或多个符号(如果括号内可以有(,则替换为[^)]*
  • \) - 结束)
  • $ - 字符串结束。

var re = /\s*\([^()]*\)$/g; 
var strs = ['09373 837 937 (mobile)','9838373838 (home)','+19383947388 (home)','(938)3947388 (mobile)'];
for (var s = 0; s < strs.length; s++) {                  // Demo
  document.body.innerHTML += "Replacing in \"<i>" + strs[s] + "</i>\"... ";
  document.body.innerHTML += "Result: <b>\"" + strs[s].replace(re, '') + "\"</b><br/>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多