问题描述:

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:

  • The: 4
  • beautiful: 2
  • tree: 2
  • garden
  • in: 2

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:

  • The: 4
  • beautiful tree: 2
  • tree: 1
  • beautiful: 1
  • garden
  • in: 2

I´m not really firm with RegExp. Do you have any Tips for me? Thank you

网友答案:

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 }
相关阅读:
Top