【问题标题】:Efficient means of identifying if two substrings are adjacent识别两个子串是否相邻的有效方法
【发布时间】:2016-08-04 22:43:36
【问题描述】:

我正在使用 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>
```

【问题讨论】:

标签: javascript node.js string typescript


【解决方案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

【讨论】:

    【解决方案2】:

    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;
    

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

    【讨论】:

    • 注意“除了一些可能的空白”。
    猜你喜欢
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    相关资源
    最近更新 更多