Debaditya Debaditya - 3 months ago 11
Javascript Question

regex : Parse a sentence

Use case

Prepare a regex which can match 1 or 2 words after 'sell|sold|selling' and matches the variable "product"

Example

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


What I did (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


I am new to regex and learning the same. Need your suggestion.

Answer

Your (.*) segment in the regex will indeed match the rest of the string because . basically means any character. If you only want to get the next two "words", you need to limit the capture with something like:

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

This would give you two capture groups, one for each of the (up to) two words following the fixed string.

Comments