[英]Finding matches using regular expression
如何找到二進制兩端包圍的連續零的長度?
例如,在10010001
,2個匹配是1001和10001
我使用了僅返回最后一個的匹配,即10001。
'1010001'.match(/1(0+)1$/g)
你需要先行斷言:
console.log('1010001'.match(/10+(?=1)/g).map(function(x) { return x.length - 1; }));
首先,將所有'1'替換為'11',然后從正則表達式中刪除$ - 。
console.log('10010001'.replace(/1/g, '11').match(/1(0+)1/g));
在正則表達式中, $
是與字符串末尾( MDN )匹配的特殊字符。
但那只是問題的一半。 String#match
捕獲了第一組中的尾隨1,並且無法為'10001'創建第二個重疊組。 嘗試使用RegExp#exec
代替。 正則表達式是有狀態的,在這種情況下,您將要為您找到的每個匹配將最后一個索引移回一個。
var re = /10+1/g;
var str = '10010001';
var matches = [];
var result;
while ((result = re.exec(str)) !== null) {
matches.push(result[0]);
re.lastIndex--;
}
console.log(matches);
而不是使用正則表達式,我會保持簡單。
const maxNumberOfZeros = Math.max(...'000000101000100000'.split('1').map(str => str.length).slice(1, -1)); console.log(maxNumberOfZeros);
RegExp
中的$
匹配字符串的結尾。
您可以使用Array.prototype.reduce()
和邏輯來評估1
和0
作為Boolean
以確定序列是否與所需模式匹配
let nums = ["1000000001010001", "0000000101", "100000000"]; let countZerosBetweenOnes = str => (res => ([...str].reduce((a, b, idx, arr) => (!!+a && !+b && arr.find((n, i) => i > idx && !!+n) && res.push(+a) , !+a && !+b && res.length && ++res[res.length - 1], b)) , res.sort((a, b) => a - b).pop() || 0))([]); nums.forEach(n => console.log(countZerosBetweenOnes(n)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.