我想正则表达式:"localhost:65536"
。
这些是可能的值/规则:":"
如果我是正确的,字符串后跟一个从 1 到 65536 的整数。
我怎样才能做到这一点?
为什么你需要一个正则表达式呢?使用常规字符串操作选项很容易实现:
public struct ConnectionData
{
public string Host;
public ushort Port;
public static bool TryParse(string connectionString, out ConnectionData data)
{
data = default(ConnectionData);
try { data = Parse(connectionString); return true; }
catch (FormatException) { return false; }
}
public static ConnectionData Parse(string connectionString)
{
var data = new ConnectionData();
var parts = connectionString.Split(new char[] { ':' }, 2);
if (parts.Length != 2 || !ushort.TryParse(parts[1], out data.Port))
throw new FormatException("Provided connectionString was not in the correct format of 'host:port'");
data.Host = parts[0];
return data;
}
};
如果你真的必须使用 RegEx:
public struct ConnectionData
{
public string Host;
public ushort Port;
private static Regex FORMAT = new Regex(@"^(?<host>[\w.-]+):(?<port>\d{1,5})$", RegexOptions.Compiled);
public static bool TryParse(string connectionString, out ConnectionData data)
{
data = default(ConnectionData);
try { data = Parse(connectionString); return true; }
catch (FormatException) { return false; }
}
public static ConnectionData Parse(string connectionString)
{
var data = new ConnectionData();
var match = FORMAT.Match(connectionString);
if (!match.Success || !ushort.TryParse(match.Groups["port"].Value, out data.Port))
throw new FormatException("Provided connectionString was not in the correct format of 'host:port'");
data.Host = match.Groups["host"].Value;
return data;
}
};