2016-08-04 29 views
0

我正在使用JavaScript/TypeScript中的nodeJS應用程序。我用正則表達式搜索文本塊,所以我有一個匹配數組。我想要一個確定這些字符串是否相鄰的簡潔方式,除了一些可能的空格。確定兩個子字符串是否相鄰的有效方法

所以我目前的應用是這樣的。我正在渲染降價,如果有兩個代碼塊,一個緊跟着另一個,我想把它們渲染爲一個標籤代碼塊。

for (let codeBlock of codeBlocks) { 
    var title = /```\s?(.*?\n)/.exec(codeBlock); 
    var code = /```.*([\s\S]*?)```/g.exec(codeBlock)[1]; 
    //console.log('Code: ' + code); 
    //console.log('Title: ' + title[1]); 
    result.push(code, title[1]); 
    var startPos = content.indexOf(code); 
    var containsSomething = new RegExp('/[a-z]+/i'); 
    //if the string between the end of the last code block and the start of this one contains any content 
    if (containsSomething.test(content.substring(startPos, lastEndPos))) { 
     result.push('n'); // Not a tabbed codeblock 
    } else { 
     result.push('y')); //Is a tabbed codeblock 
    } 
    lastEndPos = code.length + startPos + title[1].length + 6; 
    results.push(result); 
    result = []; 
} 

所以在下面的例子中輸入,我需要應標籤頂部的兩個碼塊,第三個,其不應該之間進行辨別。

``` JavaScript      //in the code example above, this would be the title 
    var something = new somethingelse();  //in the code example above, this would be the code 
``` 
``` CSS 
.view { 
    display: true; 
} 
``` 
Some non-code text... 

``` html 
<div></div> 
``` 
+2

['新正則表達式(matches.map(RegExp.escape)。加入( '\\ S *'))'](https://github.com/benjamingr/RegExp.escape/blob/master /polyfill.js)你可能也有興趣[**混合組合**](http://stackoverflow.com/questions/5752002/find-all-possible-subset-combos-in-an-array) –

+0

@PaulS。 'matches.map'看起來很有希望,你能否添加一個例子作爲答案,以便我可以標記它? –

回答

1

使用RegExp.escape (polyfill)則可以將字符串轉換成RegExp的安全版本,然後創造條件,具有可變空格匹配他們的表情,

let matches = ['foo', 'bar']; 
let pattern = matches.map(RegExp.escape).join('\\s*'); // "foo\\s*bar" 
let re = new RegExp(pattern); // /foo\s*bar/ 

現在可以申請給你的乾草堆;

re.test('foo\n\n\nbar'); // true 
re.test('foo\nbaz\n\nbar'); // false 
0

regex.exec(STR)返回一個包含索引屬性這表明你在那裏匹配字符串中開頭的對象。

/(\d{3})/.exec('---333').index

以上的回報3,這是比賽的開始。

,如果你有兩場比賽,你可以檢查他們是否是相鄰的,如果第一個匹配的指數+長度==第二場比賽的指數

var re = /(\d{3})/g; 
var str = '---333-123---'; 
var match1 = re.exec(str); 
var match2 = re.exec(str); 
(match1.index+match1[1].length) == match2.index; 

我覺得這是適用的,但我不知道如何你的代碼工作。 對不起,它不是你的例子,但我認爲這可能對你有用。

+0

注意「*某些可能的空白*除外」。 – RobG

相關問題