1

I'm looking for a regex in C#.net to extract printers from a list in a script.

This is an example:

@set nr=2
@if not exist "%userprofile%\Version%nr%.txt" goto reload
@goto koppla
:reload
@echo skrivare>"%userprofile%\Version%nr%.txt"
@del "%userprofile%\zxy-*.txt"
@call skrivare.cmd
@exit
:koppla
@%connect1% \\%Print2%\Lund-M1
@%connect2% \\%Print2%\MAR-M1
@%connect2% \\%Print2%\MAR-M2

I would like to get the names (Lund-M1, MAR-M1, MAR-M2) of the printers in a array to foreach.

I really appreciate any help on this, my mind doesn't work with Regex.

Thank you in advance!

3 Answers 3

1

You could do something quite simple, like searching for the Print2 prefix:

\\\\%Print2%\\(.*)

This gives the following output on http://www.regexer.com. You'd then need to access the first group of each Match object to grab the part of the string you are after.

enter image description here

Edit

If you want to encapsulate different print numbers use the following which allows the 2 to be exchanged with any other number.

\\\\%Print[0-9]%\\(.*)
Sign up to request clarification or add additional context in comments.

2 Comments

Fantastic! Thank you so much! I forgot to say that in the same script, there could be like @%connect2% \\%Print1%\SAR-P2 also, %Print1% is the difference. Should I do another expression for that or is there a way to implement it in the same search?
@Andreas: I've added an extra bit at the end to show how you can exchange the number to any other number.
1
(?m:(?<=^@\%connect\d\% \\\\(.*?\\)*)[^\\]+$)

will give three matches over your script, with values

Lund-M1
MAR-M1
MAR-M2

So

Regex.Matches(input, @"(?m:(?<=^@\%connect\d\% \\\\(.*?\\)*)[^\\]+$)")
     .Cast<Match>()
     .Select(m => m.Value)
     .ToArray()

gives you what you need.

This checks for line starting @%connect then any digit followed by % then pulls the last segment of any path of the form \\something\something\something\AnyNonBackslashChars

Comments

1
foreach (Match match in Regex.Matches(text, 
    @"^@%connect\d+%\s+\\\\%Print2%\\(.*?)\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline))
{
    if (match.Success)
    {
        var name = match.Groups[1];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.