gpt4 book ai didi

javascript - 正则表达式从字符串中提取一组单词

转载 作者:行者123 更新时间:2023-11-29 19:44:01 25 4
gpt4 key购买 nike

问题陈述 -

我们需要从字符串中提取一组连续出现的单词。

最简单的示例如下所示,具有预期的输入和输出。

set of words => "word1|word2|word3";

Input string => "i m word1 word2 and this is word3 word2 word1+ i am having this word2 word3.";"

Output => word1 word2
word3 word2 word1
word2 word3

注意 -- 请注意“word1+”和“word3”中没有空格。

请将此视为最简单的输入。复杂性可以达到任何程度。意味着可以有多个单词集(比如 500 个单词),我们需要从输入字符串中找到同时出现的那些单词集。

我在 javascript 中执行此操作,因此我尝试的如下。

var pattern = "word1|word2|word3";
var regobj = new RegExp('((('+pattern+')\\s?)+)', "g");

我的解决方案有什么问题?

For Input string => "i m word1word2 and this is word3word2 word1+ i am having this word2 word3.";"

it will give output as
word1word2 -- wrong
word3word2 word1 -- wrong
word2 word3

我为什么要这个?或实时用例..!

我想从一个复杂的表达式中提取单词编号。比如说

"one thousand two+three hundred four+1.3456+log(twenty)"

所以这里我需要提取

one thousand two
three hundred four
twenty

并且需要替换它各自的等效数值。

最佳答案

使用单词边界:

\b(?:word1|word2|word3)\b

Perl 中完整的正则表达式:

my $str = 'i m word1word2 and this is word3 word2 word1+ i am having this word2 word3.';
my @l = ($str =~ /((?:\b(?:word1|word2|word3)\b(?:\s|\.))+)/g);
dump@l;

输出:

("word3 word2 ", "word2 word3.")

最后一个表达式:

my $str = 'one thousand two+three hundred four+1.3456+log(twenty)';
my @l = ($str =~ /((?:\b(?:one|two|three|four|twenty|hundred|thousand)\b\s*)+)/g);
dump@l;

输出:

("one thousand two", "three hundred four", "twenty")

关于javascript - 正则表达式从字符串中提取一组单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com