使用 boost 正则表达式从字符串中提取 IP 地址?
我想知道是否有人可以帮助我,我一直在寻找正则表达式的示例,但我仍然无法理解它。
字符串如下所示:
"User JaneDoe, IP: 12.34.56.78"
"User JohnDoe, IP: 34.56.78.90"
我将如何制作一个表达式与上面的字符串匹配吗?
I was wondering if anyone can help me, I've been looking around for regex examples but I still can't get my head over it.
The strings look like this:
"User JaneDoe, IP: 12.34.56.78"
"User JohnDoe, IP: 34.56.78.90"
How would I go about to make an expression that matches the above strings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你到底想如何匹配这些,以及你还想排除什么?
将任何传入字符串与简单的
.*
相匹配很简单(但很少有用)。为了更准确地匹配这些(并添加提取用户名和/或 IP 等内容的可能性),您可以使用类似以下内容的内容:
"User ([^,]*), IP: (\\d{1 ,3}(\\.\\d{1,3}){3})"
。根据您的输入,可能仍然会遇到包含逗号的名称问题(例如“John James, Jr.”)。如果你必须考虑到这一点,那么很快就会变得更加丑陋。编辑:这里有一些代码来测试/演示上面的正则表达式。目前,这是使用 C++0x 正则表达式类——要使用 Boost,您需要稍微更改命名空间(但我相信这应该是全部)。
这会打印出用户名和 IP 地址,但格式(勉强)足够不同,以明确它正在匹配并打印出各个部分,而不仅仅是传递整个字符串。
The question is how exactly do you want to match these, and what else do you want to exclude?
It's trivial (but rarely useful) to match any incoming string with a simple
.*
.To match these more exactly (and add the possibility of extracting things like the user name and/or IP), you could use something like:
"User ([^,]*), IP: (\\d{1,3}(\\.\\d{1,3}){3})"
. Depending on your input, this might still run into a problem with a name that includes a comma (e.g., "John James, Jr."). If you have to allow for that, it gets quite a bit uglier in a hurry.Edit: Here's a bit of code to test/demonstrate the regex above. At the moment, this is using the C++0x regex class(es) -- to use Boost, you'll need to change the namespaces a bit (but I believe that should be about all).
This prints out the user name and IP address, but in (barely) enough different format to make it clear that it's matching and printing out individual pieces, not just passing entire strings through.
编辑:修复了 Davka 指出的字符串中缺少逗号的问题,并将 cmatch 更改为 smatch
Edited: Fixed missing comma in string, pointed out by Davka, and changed cmatch to smatch