Question

I'm looking for help with a regex. I have the following UNC path \\server\share1\folder1 that I would like to grab server from. The server name will always be different and sometimes be an IP address.

I have the following Expression that I have been working with but I can't seem to get it to work the way I want.

\\?.*\\

This returns the following result \\server\share\. Can someone help me just grab server and not \\server\?

Était-ce utile?

La solution

You can use this:

^\\\\.*?\\

^ is a beginning of line anchor and will match only at the beginning.

.*? is a modified version of .* so that it will match up to the match of the pattern following it; usually called to be matching 'as little as possible', in opposition to its 'greedy' counterpart.


Alternatively, you can use a negated class:

^\\\\[^\\]+\\

[^\\]+ matches any character except backslashes.


And if you want to get server without the backslashes, you should be able to use a capture group (by using parentheses) and extract the matched group (through $1 or \1):

^\\\\(.*?)\\

or

^\\\\([^\\]+)\\

Or if UNC finds any first match by default, then you can simply use [^\\]+.

Autres conseils

Try doing string.split (or its equivalent in the language you're using) with '\', then get "server" from the resulting array

You can use lookaround

(?<=^\\)[^\\]+(?=\\)

This would match server in \server\share\folder.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top