[英]How can I get the multiple texts from two sets of parentheses?
我需要從一組以上的括號中獲取多個文本,如果不多於一組,則僅需要從該組括號中獲取文本。
1)范例:
My sentence is :
A Cef (1000mg) (Sterlie Ceftriaxone) Price List.
現在,我需要獲得如下輸出:
Output :
1000mg Sterlie Ceftriaxone
2)另外,如果我只有這樣一套:Aamin A(Atenolol)價格表。
然后我的輸出應該是:阿替洛爾
我正在使用以下javascript代碼:
function myFunction() {
var str = "A Cef (1000mg) (Sterlie Ceftriaxone) Price List.";
var res = str.match(/\((.*))\)/);
document.getElementById("demo").innerHTML = res[1];
}
對於第二種情況,它是完美的工作方式,但是當我將其用於第一種情況時,它會提供此輸出。
Output :1000mg) (Sterlie Ceftriaxone
使用非貪婪的表達式/\\((.+?)\\)/gm
。 參見https://regex101.com/r/OKvbXy/1
function myFunction(text) { var res = text.match(/\\((.+?)\\)/g); var cleanedUp = res.join(' ').replace(/[()]/g,''); // remove () and join matches console.log( cleanedUp ); } myFunction("A Cef (1000mg) (Sterlie Ceftriaxone) Price List."); myFunction("Aamin A (Atenolol) Price List.");
順便說一句,您的代碼與jQuery無關( 您甚至沒有在代碼中使用它 )
我相信問題是通過使用.*
(通配符),您正在捕獲方括號和空格。
如果您使用var res = str.match(/\\(([0-9a-zA-Z]+)\\)/);
相反,它將捕獲第一個組,因為它與示例中的方括號或空格不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.