用戶可以輸入如下字串:
4409101800
16.10.10.110
4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.
16.10.10.110 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.
數字代碼始終位于字串的開頭。
我只需要一個包含前 6 位數字的字串,包括點(如果有的話)。
像這樣:
440910
16.10.10
我試圖創建一個正則運算式,但失敗了。
你能幫我找到一個優雅的解決方案來完成這項任務嗎?
uj5u.com熱心網友回復:
捕獲前 5 位數字并在其間添加可選的許多點,然后匹配最后一個數字:
(\d\.*){5}\d
正則運算式101
uj5u.com熱心網友回復:
如果您可以非常原始地進行操作,一個簡單的回圈并檢查每個字符是否為數字,您可以執行以下操作:
const input = [
`4409101800`,
`16.10.10.110`,
`4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.`,
`16.10.10.110 - Lorem Ipsum is simply dummy text of the printing`
]
const getFirstSixNumbers = (str) => {
const strArr = str.split('');
let digitCount = 0;
let i = 0;
let output = '';
while (digitCount < 6) {
const nextChar = strArr[i];
if (is_numeric(nextChar)) digitCount ;
output = nextChar;
i ;
}
return output;
}
input.forEach(item => console.log(getFirstSixNumbers(item)));
//check if number
//source: https://stackoverflow.com/questions/8935632/check-if-character-is-number
function is_numeric(str) {
return /^\d $/.test(str);
}
uj5u.com熱心網友回復:
您可以運行一個for回圈來檢查每個字符,然后回傳slice()包含前 6 位數字的字串。
const arr=["4409101800",
"16.10.10.110",
"4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"Too 1 few 2.34 digits 5 available",
"And finally: 16.10.10.110 - Lorem Ipsum is simply dummy text of the printing and typesetting industry."];
function first6(str){
for (var rx=/\d/, n=i=0;i<6&&n<str.length;n )
if(rx.test(str[n])) i ;
return str.slice(0,n)
}
arr.forEach(s=>console.log(first6(s)));
// And here is another way, solely using a regular expression:
const rx2=/\D*?(\d\D*?){6}/;
arr.forEach(s=>console.log((s.match(rx2)??[""])[0]));
第二種基于正則運算式的解決方案的行為更為嚴格,因為如果在輸入字串中找不到所需的 6 位數字,它將回傳一個空字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/491137.html
標籤:javascript 正则表达式
