gpt4 book ai didi

javascript - 正则表达式 : Parse a sentence

转载 作者:行者123 更新时间:2023-11-30 15:53:17 25 4
gpt4 key购买 nike

用例

准备一个正则表达式,可以匹配'sell|sold|selling'之后的1个或2个词,并匹配变量“product”

示例

Sentence - "John wants to sell 200$ XYZ laptop and buy ABC PC"

if product = "ABC" , then it should not match

If product = "XYZ" , then it should match

我做了什么 (javascript)

var desc = "John wants to sell 200$ XYZ laptop and buy ABC PC"
var product = "ABC"

var reg_s="sell\|selling\|sold (.*)" + product;
var re_s= new RegExp(reg_s,'gi');
var sell = desc.match(re_s);

In the above code , the whole string after 'sell' is getting matched - but it should not match for ABC. Need to match only those products which appear 1,2 words after sell|sold|selling. For eg: product = XYZ should match

我是正则表达式的新手,正在学习相同的内容。需要您的建议。

最佳答案

正则表达式中的 (.*) 段确实会匹配字符串的其余部分,因为 . 基本上表示任何字符。如果您只想获取接下来的两个“单词”,则需要使用以下内容限制捕获:

(\S+)\s*(\S*)

这将为您提供两个捕获组,一个用于固定字符串后面的(最多)两个单词中的每一个。


此外,我建议使用以下内容作为基准:

var desc = "John wants to sell 200$ XYZ laptop and buy ABC PC";
var product = "ABC";

var reg_s="(sell|sold|selling)\\s+(\\S*\\s*\\S*)";
var re_s= new RegExp(reg_s,'gi');
var sell = re_s.exec(desc);
alert(sell[2]);

这为您提供了一个实际的捕获组数组,而 string.match 给您的数组将是一个字符串数组,没有拆分各个捕获组。

关于javascript - 正则表达式 : Parse a sentence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38987027/

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