A regular expression that returns a constant value as part of a match

I have a regular expression to match two different formats: \ = (? [0-9] +) \? \\ + (? [0-9] +) \?

This should return 9876543 as a value for ; 1234567890123456? + 1234567890123456789012345123 = 9876543?
and ; 1234567890123456? +9876543? I would like to be able to return another value along with an agreed "value".

So, for example, if the first line was matched, I would like it to return:

Cost: 9876543 Format: LongFormat


And if it matches in the second line:

Cost: 9876543 Format: ShortFormat


Is it possible?

+3
3

, , , , .

#:

var regex = new Regex(@"\=(?<Long>[0-9]+)\?|\+(?<Short>[0-9]+)\?");
string test1 = ";1234567890123456?+1234567890123456789012345123=9876543?";
string test2 = ";1234567890123456?+9876543?";

var match = regex.Match(test1);
Console.WriteLine("Long: {0}", match.Groups["Long"]);     // 9876543
Console.WriteLine("Short: {0}", match.Groups["Short"]);   // blank
match = regex.Match(test2);
Console.WriteLine("Long: {0}", match.Groups["Long"]);     // blank
Console.WriteLine("Short: {0}", match.Groups["Short"]);   // 9876543

, , regex.Groups [GroupName] , . Success , , (match.Groups [ "Long" ]. ).

UPDATE: :

static void Main(string[] args)
{
    var regex = new Regex(@"\=(?<Long>[0-9]+)\?|\+(?<Short>[0-9]+)\?");
    string test1 = ";1234567890123456?+1234567890123456789012345123=9876543?";
    string test2 = ";1234567890123456?+9876543?";

    ShowGroupMatches(regex, test1);
    ShowGroupMatches(regex, test2);
    Console.ReadLine();
}

private static void ShowGroupMatches(Regex regex, string testCase)
{
    int i = 0;
    foreach (Group grp in regex.Match(testCase).Groups)
    {
        if (grp.Success && i != 0)
        {
            Console.WriteLine(regex.GroupNameFromNumber(i) + " : " + grp.Value);
        }
        i++;
    }
}

0- , .NET

+3

, , . .

. , :

if match(\=(?[0-9]+)\?) then
    return 'Value: ' + match + 'Format: LongFormat'
else if match(\+(?[0-9]+)\?) then
    return 'Value: ' + match + 'Format: ShortFormat'

( , .)

+2

, , , , , , , , .

" ", .

:

Input.replaceAll( /[+=][0-9]+(?=\?)/ , formatValue );

formatValue : function(match,groups)
{
    switch( left(match,1) )
    {
        case '+' : Format = 'Short';   break;
        case '=' : Format = 'Long';    break;
        default  : Format = 'Unknown'; break;
    }

    Value : match.replace('[+=]');

    return 'Value: '+Value+' Format: ' + Format;
}

, , regex, formatValue , , .

You have not indicated which implementation you are using, so it may or may not be possible for you, but it is definitely worth checking out.

+1
source

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


All Articles