horgh
horgh

Reputation: 18563

How to make regular expression match if a group of symbols is repeated only?

I need a regular expression that may match dates. However the delimiter of day, month and year may differ. It may be a dot, a dash, a slash...

What I have is

^([012]?[1-9]|3[01])[\\.\\-\\/\\\\](0?[1-9]|1[012])[\\.\\-\\/\\\\](19|20)\\d{2}$

So it's

([012]?[1-9]|3[01]) --the day part
(0?[1-9]|1[012])    --the month part
(19|20)\\d{2}       --the year part

The delimiter is repeated twice and, according to my current expression [\\.\\-\\/\\\\], may be different...I mean, it matchs, say:

01.01-1986

While I want it to match only when there two dots, or two dashes, or two of whatever the delimiter part allows...So the example given above should NOT match.

I suppose it can somehow be done with grouping pattern of regular expressions. But I have no idea of how to apply this. Also I found myself to be absolutely not aware of how to google this...

Could anyone push me towards the right direction?


P.S.: I've recently watched SO Regular Expression to match valid dates...In my case I do understand that it'll match the 31st in months that do not have it, and all the days absent in February...it's all alright...


In Java I currently use the following code:

String value = "31/12/2086";
String pattern = ...
boolean result = value.matches(pattern);

In C#

string value = "01.01.2014";
string pattern = "";
bool result = Regex.IsMatch(value, pattern);

If there is a way to do what I want to, it would be great if the solution would be appliable to both these languages...Are Java and C# regular expressions compatible?

Upvotes: 2

Views: 1977

Answers (1)

Pshemo
Pshemo

Reputation: 124275

You can use \\x in your regular expression where x is group number. It represents same string that is matched by group x. So in your case you can use something like

someRegex([.\\-/\\\\])someOtherRegex\\1anotherRegex
          ^^^^^^^^^^^               ^^^
            group 1                 here should appear same string as in group 1

example

String regex = "someRegex([.\\-/\\\\])someOtherRegex\\1anotherRegex";
System.out.println("someRegex.someOtherRegex.anotherRegex".matches(regex));
System.out.println("someRegex.someOtherRegex-anotherRegex".matches(regex));
System.out.println("someRegex-someOtherRegex-anotherRegex".matches(regex));

output:

true
false
true

Upvotes: 2

Related Questions