Match pattern [0-9] - [0-9] - [0-9], but without matching [0-9] - [0-9]

I'm not sure how to do this with regex (or, if possible, I'm new to regex). I have an angle value that the user enters and I'm trying to check it. It is in the form of degrees-minutes-seconds. The problem I am facing is that if the user mistakenly uses the second part, I need to catch this error, but my match for degrees-minutes is success.

Perhaps the method will explain better:

    private Boolean isTextValid(String _angleValue) {

        Regex _degreeMatchPattern = new Regex("0*[1-9]");
        Regex degreeMinMatchPattern = new Regex("(0*[0-9]-{1}0*[0-9]){1}");
        Regex degreeMinSecMatchPattern = new Regex("0*[0-9]-{1}0*[0-9]-{1}0*[0-9]");

        Match _degreeMatch, _degreeMinMatch, _degreeMinSecMatch;

        _degreeMinSecMatch = degreeMinSecMatchPattern.Match(_angleValue);
        if (_degreeMinSecMatch.Success)
            return true;

        _degreeMinMatch = degreeMinMatchPattern.Match(_angleValue);
        if (_degreeMinMatch.Success)
            return true;

        _degreeMatch = _degreeMatchPattern.Match(_angleValue);
        if (_degreeMatch.Success)
            return true;

        return false;
    }
}

-, -- , . , ? .

: 45-23-10 . 45-23 ; 0 . , 45-23-1 = , MinMatchPattern , .

: , , . 45, .

+3
5

-, , {1} ​​ .

-, , -, ( , , ), ^ $ , , .

"^\d {1,3} -\d {1,2} (-\d {1,2})? $".

: ^ . \d , {1,3}, . , , . , . , ? . $ , . , 222-33-44 222-33, 222-3344 222-33-abc.

, , , , . , ( ). . , , , ; DMS 359-59-59, 999-99-99, . (, "(3 [0-5]\d | [1-2]\d {2} |\d {1,2})" 0 359, 3, 0-5, 0-9, 3- , 1 2, ), , , , .

+2

, " 3 ", {m,}. , , :

`[0-9](-[0-9]){2,}`

[0-9] \d: \d(-\d){2,}

+4

, .

+1

, ,

(?<degrees>0*[0-9])-?(?<minutes>0*[0-9])(?:-?(?<seconds>0*[0-9]))?$

.

; , //. , , , .

0

Maybe you should try something like this and check for empty / invalid groups:

Regex degrees = new Regex(
                @"(?<degrees>\d+)(?:-(?<minutes>\d+))?(?:-(?<seconds>\d+))?");
string[] samples = new []{ "123", "123-456", "123-456-789" };
foreach (var sample in samples)
{
    Match m = degrees.Match(sample);
    if(m.Success)
    {
        string degrees = m.Groups["degrees"].Value;
        string minutes = m.Groups["minutes"].Value;
        string seconds = m.Groups["seconds"].Value;
        Console.WriteLine("{0}°{1}'{2}\"", degrees,
            String.IsNullOrEmpty(minutes) ? "0" : minutes,
            String.IsNullOrEmpty(seconds) ? "0" : seconds
        );
    }
}
0
source

Source: https://habr.com/ru/post/1766809/


All Articles