karthick
karthick

Reputation: 12176

How to use regular expression to get the number of matches in a string?

I started learning regular expression recently. I have a small problem statement now.

I am having a pattern like this

var pattern = /^(?:hawaian(?:beach|pizza|hotel))$/gim;
var text = "hawaian hotel is near hawaian beach. In the hawaian hotel they sell hawaian pizza";

I want to actually match hawaian hotel, hawaian beach and hawaian pizza in this text.

But the pattern is returning true only for conditions like hawaianhotel || hawaianbeach || hawaianpizza.

So i tried like this

 var text = "hawaianhotel is near hawaianbeach. In the hawaianhotel they sell hawaianpizza";

But this is also not working.

Only this one is working

var matches = pattern.exec('hawaian*');

Upvotes: 3

Views: 97

Answers (3)

user1858213
user1858213

Reputation:

var pattern = /(?:hawaian[ ](?:beach|pizza|hotel))/gim;

Upvotes: 0

Preston
Preston

Reputation: 1346

(?:hawaiian[ ](?:beach|pizza|hotel)) 

this will match on hawaiian pizza

Notice the [ ] if for example you wanted to match hawaiian2hotel you would do [0-9] or [2] or if you wanted to match "hawaiian (arbitrary number of spaces) hotel" you would do [ ]* (zero or more) or [ ]+ (one or more)

also, this is a wonderful tool http://iblogbox.com/devtools/regexp/

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208455

Your pattern uses beginning and end of string anchors, so you would only match strings if the pattern matches the entire string. Remove the ^ and $ and you should be okay. Note that I also added a space so that you can match "hawaian hotel" instead of "hawaianhotel".

var pattern = /(?:hawaian (?:beach|pizza|hotel))/gim;

Upvotes: 2

Related Questions