如何在以 Typescript 结尾的不同行的字符串中查找子字符串索引

问题描述 投票:0回答:1

我有两根弦

  1. abc
    \r\n
    def
  2. c
    \n
    de

我需要在字符串 1 中找到字符串 2 的索引。

我显然不能使用indexOf(),所以我需要一些可以像它一样工作的东西,但考虑到不同的行结尾。

我无法修改原始字符串,因为我需要原始字符串中的子字符串索引。如果我用

\r\n
替换所有
\n
,它会弄乱原始索引,所以我必须以某种方式恢复它们。

javascript typescript string substring line-endings
1个回答
0
投票

(FWIW,这个问题没有任何 TypeScript 特定的内容。只是 JavaScript。)

您可以通过使用交替

\r\n|\r|\n
将您要查找的字符串转换为正则表达式来做到这一点,并且确保转义中间的部分(请参阅这个问题的答案)那个)。

TypeScript 类型注释被注释掉的示例:

// From https://stackoverflow.com/a/3561711/157247
function escapeRegex(string) {
    return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}

function test(str/*: string */, substr/*: string*/) {
    // Split up the text on any of the newline sequences,
    // then escape the parts in-between,
    // then join together with the alternation
    const rexText = substr
        .split(/\r\n|\n|\r/)
        .map((part) => escapeRegex(part))
        .join("\\r\\n|\\n|\\r");
    // Create the regex
    const re = new RegExp(rexText);
    // Run it
    const match = re.exec(str);
    if (match) {
        console.log(`Found ${JSON.stringify(match[0])} at index ${match.index} in ${JSON.stringify(str)}`);
    } else {
        console.log(`Not found`);
    }
}


test("abc\r\ndef", "c\nde");

© www.soinside.com 2019 - 2024. All rights reserved.