Count Number of Matches of a Regex in JavaScript

Count number of matches of a regex in Javascript

tl;dr: Generic Pattern Counter

// THIS IS WHAT YOU NEED
const count = (str) => {
const re = /YOUR_PATTERN_HERE/g
return ((str || '').match(re) || []).length
}

For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration:

/* *  Example */
const count = (str) => { const re = /[a-z]{3}/g return ((str || '').match(re) || []).length}
const str1 = 'abc, def, ghi'const str2 = 'ABC, DEF, GHI'
console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)

JAVASCRIPT: Count the number of REGEX results

you need the global regex flag (g) to match all occurrences and then simply get the length of the result. the ? makes the .* ungreedy, otherwise it would only once fit the first and the last bracket as regexps are greedy by default.

var source = "{example1}{example2}{example3}";
var count = source.match(/\{.*?\}/g).length;

Javascript regular expression to match words and count the number of times each word has occured

You can use the String.prototype.replace() function. It won't be one line of code, but it'll be pretty simple:

var regex = /((word1?)|(word2?)|(word3?)|(word4?)|(word5 ?)|(word6?)|(word7?))/gmi;

var counts = {};
var sourceText = yourSourceTextWithWordsInIt;

sourceText.replace(regex, function(_, matched) {
matched = matched.toLowerCase();
counts[matched] = (counts[matched] || 1) + 1;
});

Then the counts object will contain exactly what you described. The .replace() function on the String prototype can take a function as its second parameter. Such a function will be called repeatedly when the pattern has the "g" flag. Each call to the function will include as the first parameter the entire matched substring, and the subsequent parameters will be the parenthesized group matches from the regex.

Regex match count of characters that are separated by non-matching characters

Hey I think this would a simple but working one:

( *?[0-9a-zA-Z] *?){10,}

Breaking the regex down:

  1. ( *? --------It can start with space(s)
  2. [0-9a-zA-Z] -Followed with the alphanumeric values
  3. *?) ---------It can end with space(s)
  4. {10,} -------Matches this pattern 10 or more times

Key: When I look at the count for regexes, it applies to the group, i.e., the things in the brackets "()", this case, multiple spaces followed ONE from the alphanumeric values followed by spaces are still counted as one match. Hope it helps. :)

use markjs to count number of regex matches of certain class

It's kinda simple. You can either use the each or the done callback, both provde a counter. With the done callback you don't need to count it yourself, you receive the number of all marks, thus it's easier for you. Furthermore the done callback is better for performance, since it isn't necessary to call the function on each mark.

Here's the code:

var instance = new Mark(".context"),  negativeCounter = 0,  positiveCounter = 0;
//negative assertionsinstance.markRegExp(/not significant/g, { className: "negative", done: function(counter) { negativeCounter += counter; }});instance.markRegExp(/not associated/g, { className: "negative", done: function(counter) { negativeCounter += counter; }});instance.markRegExp(/no association/g, { className: "negative", done: function(counter) { negativeCounter += counter; }});//positive assertionsinstance.markRegExp(/is associated/g, { className: "positive", done: function(counter) { positiveCounter += counter; }});instance.markRegExp(/are associated/g, { className: "positive", done: function(counter) { positiveCounter += counter; }});instance.markRegExp(/was associated/g, { className: "positive", done: function(counter) { positiveCounter += counter; }});
document.write("Positive counter: " + positiveCounter + ", Negative counter: " + negativeCounter);
<script src="https://cdn.jsdelivr.net/mark.js/8.8.3/mark.min.js"></script><div class="context">  not significant not significant not associated no association is associated are associated was associated</div>

How to count string occurrence in string?

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

var temp = "This is a string.";var count = (temp.match(/is/g) || []).length;console.log(count);

How to find the exact individual count of array of string in array of sentences efficiently?

You could split the strings and filter by name and get the length of the array.

var names = ["jhon", "parker"],    sentences = ["hello jhon", "hello parker and parker", "jhonny jhonny yes parker"],    parts = sentences.join(' ').split(/\s+/),    result = names.map(name => parts        .filter(s => s === name)        .length    );
console.log(result);

Counting occurrences of a word in a string with Javascript using match

The regular expression is literally matching word, as variable word is never indicated. There is no match found in the string myText so it's null, hence the error. Try like this:

myText.match(new RegExp(word, "g")).length

This uses the RegExp constructor, which takes in two arguments: the pattern and the flags. The above will pass the actual value of word instead of the literal word, and the flag g. It's equivalent to /word/g except word is correctly matched to what word is passed. See the following snippet:

const myText = "cat dog stop rain cat"
myText.split(" ").forEach((word) => { const numberOfOccurrences = myText.match(new RegExp(word, "g")).length console.log(`${word} - ${numberOfOccurrences}`)})

Count number of times a regular expression is matched in a string

For this particular scenario, you could do something like this:

Regex.Match(input, pattern).Groups[1].Captures.Count

The element in Groups[0] would be the entire match, so that's not helpful for what you need. Groups[1] will contain the entire (\\tChannel [0-9]* \(mV\))* section, which includes all the repeats. To get the number of times it repeates you use .Captures.Count

Sample based on your example:

Regex.Match(
@"Time\tChannel 1 (mV)\tChannel 2 (mV)\tChannel 3 (mV)\tChannel 4 (mV)\tChannel 5 (mV)\tChannel 6 (mV)\tChannel 7 (mV)\tChannel 8 (mV)\tChannel 1_cal (mg/L)\tChannel 2_cal ()\tChannel 3_cal ()\tChannel 4_cal ()\tChannel 5_cal ()\tChannel 6_cal ()\tChannel 7_cal ()\tChannel 8_cal ()\tMotor 1 (mm)\tMotor 2 (mm)",
@"Time(\\tChannel [0-9]* \(mV\))*"
).Groups[1].Captures.Count;

I apologize for the poor formatting there, but this should show you how this can be done at the very least.

The examples given around Regex.Matches(...).Count won't work here because it's a single match. You can't just use Regex.Match(...).Groups.Count either because you only have one group specified, which leaves this with 2 groups returned from the match. You need to look at your specific group Regex.Match(...).Groups[1] and get the count from the number of captures in that group.

Also, you can name the groups which might make it a little bit clearer on what is happening. Here's an example:

Regex.Match(
@"Time\tChannel 1 (mV)\tChannel 2 (mV)\tChannel 3 (mV)\tChannel 4 (mV)\tChannel 5 (mV)\tChannel 6 (mV)\tChannel 7 (mV)\tChannel 8 (mV)\tChannel 1_cal (mg/L)\tChannel 2_cal ()\tChannel 3_cal ()\tChannel 4_cal ()\tChannel 5_cal ()\tChannel 6_cal ()\tChannel 7_cal ()\tChannel 8_cal ()\tMotor 1 (mm)\tMotor 2 (mm)",
@"Time(?<channelGroup>\\tChannel [0-9]* \(mV\))*"
).Groups["channelGroup"].Captures.Count;

Count matches at the end of a string

You need to work on the first element of the returned array:

string.match(/(-1)*$/)[0].length/2

Find the length of first element which is the matched string of "-1" at the end and divide by 2 since the string "-1" is of length 2.

To quote from MDN String.prototype.match():

Return value

If the string matches the expression, it will return an Array
containing the entire matched string as the first element, followed by
any results captured in parentheses. If there were no matches, null is
returned.

function count() {  console.log(string.match(/(-1)*$/)[0].length / 2)}
var string = "1"// 0count();
string = "1-1"// 1count();
string = "1-1-1"// 2count();
string = "1-2-1"// 1count();
string = "1-2-1-2-1"// 1count();
string = "2-1-1-1-1"// 4count();
string = "1-1-2"// 0count();


Related Topics



Leave a reply



Submit