本文介绍了在 C++ 中解析它的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有以下格式的服务器地址"列表:

In my program, I have a list of "server address" in the following format:

host[:port]

这里的括号表示port是可选的.

The brackets here, indicate that the port is optional.

  • host 可以是主机名、IPv4 或 IPv6 地址(可能采用括号括起来"的表示法).
  • port,如果存在,可以是数字端口号或服务字符串(如:http"或ssh").
  • host can be a hostname, an IPv4 or IPv6 address (possibly in "bracket-enclosed" notation).
  • port, if present can be a numeric port number or a service string (like: "http" or "ssh").

如果 port 存在且 host 是 IPv6 地址,host 必须" 符号(例如:[::1])

If port is present and host is an IPv6 address, host must be in "bracket-enclosed" notation (Example: [::1])

以下是一些有效的例子:

Here are some valid examples:

localhost
localhost:11211
127.0.0.1:http
[::1]:11211
::1
[::1]

还有一个无效的例子:

::1:80 // Invalid: Is this the IPv6 address ::1:80 and a default port, or the IPv6 address ::1 and the port 80 ?
::1:http // This is not ambigous, but for simplicity sake, let's consider this is forbidden as well.

我的目标是将这些条目分成两部分(显然是hostport).我不在乎 hostport 是否无效,只要它们不包含非括号括起来的 : (290.234.34.34.5对于host是可以的,在下一个过程中会被拒绝);我只是想把这两个部分分开,或者如果没有 port 部分,以某种方式知道它.

My goal is to separate such entries in two parts (obviously host and port). I don't care if either the host or port are invalid as long as they don't contain a non-bracket-enclosed : (290.234.34.34.5 is ok for host, it will be rejected in the next process); I just want to separate the two parts, or if there is no port part, to know it somehow.

我试图用 std::stringstream 做一些事情,但我想到的一切似乎都很老套而且不是很优雅.

I tried to do something with std::stringstream but everything I come up to seems hacky and not really elegant.

你会如何在 C++ 中做到这一点?

How would you do this in C++ ?

我不介意 C 中的答案,但首选 C++.也欢迎任何 boost 解决方案.

I don't mind answers in C but C++ is prefered. Any boost solution is welcome as well.

谢谢.

推荐答案

你看过 boost::spirit?不过,这对你的任务来说可能有点矫枉过正.

Have you looked at boost::spirit? It might be overkill for your task, though.

这篇关于在 C++ 中解析它的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:05