我正在努力在不使用 Split 或任何其他類似函式的情況下使用正則運算式獲取字串的部分,這是我的場景:
我有這個文本U:BCCNT.3;GO,我想將不同的部分分開,但是中間的符號我設法用這個正則運算式得到了第一個,/(. ):/.exec(value)這給了我第一個詞,直到冒號(:),這些是價值
第二節 BCCNT
BCCNT.3;GO-> 沒有U:所以字串也可能不包含冒號,所以對于第二部分,邏輯將是any text that is between : and . or any text ending with . and nothing infront
第三節.3->any text starting with a . and ending with nothing or anytext staring with a . and ending with a ; semicolon
第四節;GO->any text starting with a ; and ending with nothing
編輯 ,最好在單獨的變數上,如
const sectionOne = regex.exec(value);
const sectionTwo = regex.exec(value);
const sectionThree = regex.exec(value);
const sectionFour = regex.exec(value);
并且哪個值與模式不匹配,變數將是undefined或 null 或任何空字串
uj5u.com熱心網友回復:
這是一個正則運算式方法,為每個可能的組件使用 4 個單獨的可選捕獲組:
var input = "U:BCCNT.3;GO";
var re = /^([^:] :)?([^.] )?(\.[^;] )?(;.*)?$/g;
var m;
m = re.exec(input);
if (m) {
console.log(m[1], m[2], m[3], m[4]);
}
uj5u.com熱心網友回復:
就像是
/^(?:([^:]*):)?([^.]*)\.(?:([^;]*);(.*))?/
例如:
const s = 'U:BCCNT.3;GO';
const m = s.match(/^(?:([^:]*):)?([^.]*)\.(?:([^;]*);(.*))?/);
console.log(m);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/336642.html
標籤:javascript 正则表达式 细绳
