【问题标题】:TypeScript - grab certain text from stringTypeScript - 从字符串中获取某些文本
【发布时间】:2022-07-06 14:08:41
【问题描述】:

我有以下文本模式:

test/something

test/ 模式永远不会改变,只会改变它后面的单词。我想抓住something,基本上是test/ 之后的那个词。但是,它也可以出现在一个句子中,例如:

Please grab the word after test/something thank you.

在这种情况下,我只想获取something,而不是thank you

我写了以下代码:

const start = text.indexOf('test/');
const end = text.substring(start).indexOf(' ') + start;
const result = text.substring(start, end).replace('test/', '');

这有效,但前提是模式在带有空格的句子中。对于 每个 情况,即使输入字符串只是 test/something 之前或之后没有任何内容,我该如何克服这个问题?

【问题讨论】:

    标签: javascript string


    【解决方案1】:

    我会改用正则表达式。匹配test/,然后匹配并捕获除空格以外的任何内容,然后提取第一个捕获组。

    const text = 'Please grab the word after test/something thank you';
    const word = text.match(/test\/(\S+)/)?.[1];
    console.log(word);

    在现代环境中,寻找test/ 会更容易一些 - 不需要捕获组。

    const text = 'Please grab the word after test/something thank you';
    const word = text.match(/(?<=test\/)\S+/)?.[0];
    console.log(word);

    【讨论】:

      【解决方案2】:

      使用正则表达式和正则表达式并捕获到第一个单词边界:

      const extract = (s) => s.match(/(?<=test\/).+?\b/);
      
      console.log(extract('test/something'));
      console.log(extract('Please grab the word after test/something thank you.'));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-16
        • 1970-01-01
        • 1970-01-01
        • 2017-06-21
        • 2017-06-16
        • 1970-01-01
        相关资源
        最近更新 更多