TypeScript-从字符串中获取特定文本



我有以下文本模式:

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,前后没有任何内容,我该如何克服这一问题?

我会使用正则表达式。匹配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);

使用一个带有正向查找的正则表达式((?<=...)),并对第一个单词边界(b)之前的任何内容执行非贪婪捕获(.+?):

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

最新更新