![](/img/trans.png)
[英]Get only contents from capturing parenthesis of a Regular Expression in Javascript
[英]How to remove all parenthesis and their contents from a string using a regular expression or pure JavaScript and retain other text format
目前我正在文本區域內輸入文本,並在單擊表單的提交按鈕時,我主要使用.replaceAll(); 對文本應用一些更改; js 方法並將其作為 div 中的段落打印出來。
如果我在文本區域中輸入已經有換行符和括號的文本,我希望我的腳本剝離/刪除所有括號以及括號內的內容,並保持所有換行符不變。
我已經嘗試了以下正則表達式 + js function 和示例文本,但是引入了一些格式問題(刪除了一些換行符,括號后面的文本與刪除括號的前一行中的文本位於同一行)
正則表達式+js代碼:
updatedText = updatedText.replaceAll(/\s*\(.*?\)\s*/g, '');
樣本輸入:
06.abbaa(bbbbadf)
01.lijer ttt
06.foo(sample)dddddddddd(garbage)
06.text(lksdhfljkld)20001(kkkkkksssss)
01.asdfg
13.fffffffff(fdsgggg/asdfasdf)
03.ggggggg(defg/abc)
18.abc 123abc
blahblah
qqqqqq
anon
06.barbarbar
10.foobar
18.fooistbar
12.blahhhh(moreblah/blah)
15.2035number(test)(test0/2test)
12.testing morewords
03.random(blahhh)(blahahaha/morerandomstuff)
17.anotherrandomtextstring
11.string
testy(mctest)
isTestingStrings
11.string
11.string
11.string
在不應該合並行時輸出的結果是:
06.abbaa01.lijer ttt
06.foodddddddddd06.text2000101.asdfg
13.fffffffff03.ggggggg18.abc 123abc
blahblah
qqqqqq
anon
06.barbarbar
10.foobar
18.fooistbar
12.blahhhh15.2035number12.testing morewords
03.random17.anotherrandomtextstring
11.string
testyisTestingStrings
11.string
11.string
11.string
為什么用空字符串替換匹配的文本會導致從字符串中刪除換行符,以及如何在我的腳本中解決此問題。 是否有更好的正則表達式來處理這個問題,或者這是否需要編寫一個自定義的 js 解析器?
您是否嘗試過以下操作?
inputString.replace(/\([^)]*\)/g,"")
s=`06.abbaa(bbbbadf) 01.lijer ttt 06.foo(sample)dddddddddd(garbage) 06.text(lksdhfljkld)20001(kkkkkksssss) 01.asdfg 13.fffffffff(fdsgggg/asdfasdf) 03.ggggggg(defg/abc) 18.abc 123abc blahblah qqqqqq anon 06.barbarbar 10.foobar 18.fooistbar 12.blahhhh(moreblah/blah) 15.2035number(test)(test0/2test) 12.testing morewords 03.random(blahhh)(blahahaha/morerandomstuff) 17.anotherrandomtextstring 11.string testy(mctest) isTestingStrings 11.string 11.string 11.string`; console.log(s.replace(/\([^)]*\)/g,""))
從字符串中刪除新換行符的原因是換行符被視為空格字符,並且與正則表達式中的兩個\s
匹配。 如果要保留換行符但要刪除括號前后的空格和制表符,請將\s
更改為[\t ]
:
updatedText = updatedText.replaceAll(/[\t ]*\(.*?\)[\t ]*/g, '');
如果您從未打算刪除空格字符,而只想刪除括號以及其中的文本,則只需從您的正則表達式中刪除\s*
序列:
updatedText = updatedText.replaceAll(/\(.*?\)/g, '');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.