Click here to Skip to main content
15,671,318 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've the following text
...bla bla bla 19 March 2023 bla bla bla...

and the following regular expression to match months' names

Is it possible to know what's the position inside the regular expression of the matched month's name?

For instance: January = 0, February = 1, March = 2 and so on.

What I have tried:

var string = "...bla bla bla 19 March 2023 bla bla bla...";

var match = string.match(/January|February|March|April|May|June|July|August|September|October|November|December/g);

console.log(match); // March
Updated 11-Mar-23 7:30am
PIEBALDconsult 10-Mar-23 17:55pm    
If you create your Regular Expression specifically to do so, then I assume you can get close to that.
I'm guessing you want to have an easy way to determine _which_ month name was matched.
I use only C# and .net's Regular Expressions -- which is a richer implementation than Javascript -- so what I come up with may not work for you.

RegExp.prototype.exec() - JavaScript | MDN[^] returns an object with an index property.
Share this answer
LB2371 22-Feb-23 4:57am    
Are you sure your answer is relevant to my question? That index property is the matched month position inside string, not inside regex (that I need to know).
As a workaround you may search the result inside the regular expression pattern.
Share this answer
This is C#, .net, and Linq, so I doubt you can use it, but maybe someone else can and maybe it will give you an idea.

The groups will be named "1" through "12" (group "0" is the overall match) so we can test which group had a successful match and parse its name to an integer.

int month = System.Int32.Parse
    "bla bla bla 19 March 2023 bla bla bla"
  ) [ 0 ].Groups.OfType<System.Text.RegularExpressions.Group>().First ( x => x.Success && ( x.Name != "0" ) ).Name
) % 12 ;

Error handling is left as an exercise.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900