簡體   English   中英

使用正則表達式查找匹配項

[英]Finding matches using regular expression

如何找到二進制兩端包圍的連續零的長度?

例如,在10010001 ,2個匹配是1001和10001

  • 1001零的長度是2
  • 10001零的長度是3

我使用了僅返回最后一個的匹配,即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);

而不是使用正則表達式,我會保持簡單。

  1. 將字符串拆分為'1'
  2. 獲取每個部分的長度
  3. 刪除第一個和最后一個部分長度,因為它們沒有被'1'包圍
  4. 找到最高的部分長度

 const maxNumberOfZeros = Math.max(...'000000101000100000'.split('1').map(str => str.length).slice(1, -1)); console.log(maxNumberOfZeros); 

RegExp中的$匹配字符串的結尾。

您可以使用Array.prototype.reduce()和邏輯來評估10作為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM