我不熟悉 Javascript 正則運算式。誰能告訴我如何使用匹配或替換將“Minus162Plus140”之類的字串轉換為“-162,140”,或將“Plus162Minus140”轉換為“162,-140”?提前非常感謝!
uj5u.com熱心網友回復:
在上一個答案的基礎上,您還需要處理其他情況,例如“Plus162Minus140”:
text = "Minus162Plus140";
text = text.replace(/^Minus/, "-"); // Handle when Minus comes first
text = text.replace("Minus", ",-"); // And second
text = text.replace(/^Plus/, ""); // Handle when Plus comes first
text = text.replace(/Plus/, ","); // And second
但是這種方法本身很脆弱,并且假定字串始終為 形式/^(Minus|Plus)\d (Minus|Plus)\d $/,您可以先使用正則運算式對其進行驗證:
if (/^(Minus|Plus)\d (Minus|Plus)\d $/) {
... do the replacement
} else {
... handle the error
}
uj5u.com熱心網友回復:
您可以只使用字串替換:
text = "Minus162Plus140";
text = text.replace("Minus", ",-");
text = text.replace("Plus", ", ");
console.log(text);
或正則運算式:
text = "Minus162Plus140";
re = /Plus/;
text = text.replace(re, ', ');
re = /Minus/;
text = text.replace(re, ',-');
// Then to remove the initial comma:
re = /^,/;
text = text.replace(re, '');
console.log(text);
uj5u.com熱心網友回復:
在下面的示例中評論了詳細資訊
const str = `Minus162Plus140 Plus162Minus140
Plus58 Minus899`;
const result = [...str.matchAll(/Minus\d |\d /g)]
//[["Minus162"],["140"],["162"],["Minus140"],["58"],["Minus899"]]
.flatMap(n =>
//will flatten all of the arrays
(n[0]
//target each sub-array convert to number
.replace('Minus', '-')));
//replace 'Minus' with '-'
console.log(JSON.stringify(result))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475357.html
標籤:javascript 正则表达式
上一篇:autograd可以處理在計算圖的相同深度中重復使用同一層嗎?
下一篇:只接受給定物件的鍵
