Reputation: 1655
Currently, I use the following RegEx in my javascript to match and count words in string. That works perfekt with this ReEx:
RegEx:
var pickRegExp = /[^\W\d]+[\u00C0-\u017Fa-zA-Z'](\w|[-'](?=\w))*/gi;
Keyword: beautiful
String: The beautiful tree in the garden. In the garden is the beautiful tree.
Output:
Now, I also want to match phrases (exactly). For e.g.
Keyword or Phrase: beautiful tree
String: The beautiful tree in the garden. In the garden is the beautiful tree. The model tree beautiful is sold out.
Output:
I´m not really firm with RegExp. Do you have any Tips for me? Thank you
Upvotes: 1
Views: 1535
Reputation: 114461
What about
/\b(Beautiful tree|..*?)\b/gi
i.e. a logical OR between the exact match and a generic word matching regexp?
s = ("The beautiful tree in the garden. In the garden is " +
"the beautiful tree. The model tree beautiful is sold out.");
result = {}
s.match(/\b(Beautiful tree|..*?)\b/gi).forEach(function(x) {
result[x] = (result[x]|0) + 1;
});
gives
{ " ": 15,
". ": 2,
"In": 1,
"The": 2,
"beautiful": 1,
"beautiful tree": 2,
"garden": 2,
"in": 1,
"is": 2,
"model": 1,
"out": 1,
"sold": 1,
"the": 3,
"tree": 1 }
Upvotes: 2