识别两个子串是否相邻的有效方法

时间:2016-08-04 22:43:37

标签: javascript node.js string typescript

我正在使用JavaScript / TypeScript开发nodeJS应用程序。我正在用正则表达式搜索一个文本块,所以我有一系列匹配。我想要一种简洁的方法来识别这些字符串是否相邻,除了一些可能的空格。

所以我目前的申请是这样的。我正在渲染markdown,如果有两个代码块,一个紧接着另一个,我想将它们渲染为标签代码块。

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 个答案:

答案 0 :(得分:1)

使用RegExp.escape (polyfill)您可以将字符串转换为 RegExp-safe 版本,然后创建一个与变量空格匹配的表达式,

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

答案 1 :(得分: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;

我认为这是适用的,但我不确定您的代码是如何工作的。 很抱歉,它没有关注您的示例,但我认为这对您有用。

相关问题