如何在正则表达式中匹配以 : 或不结尾的字符串

How to match a string ending with : or not in regex

我正在使用 re2.h 并进行部分匹配。

Assume the input string is "123.45.34.5:8080". "123.45.34.5" and "8080" should be returned.

Assume input string is "123.45.34.5". "123.45.34.5" and "" should be returned, too. How to write the regex? The following code does not work.

string portRegex = "[ \r\t]*([0-9a-f]*)[ \r\t]*";
string IPRegex = "([^ \r\t]*)^[^:]*";
string alertRegexStr = IPRegex + portRegex;
m_alertRegex = new RE2(alertRegexStr.c_str());

   bool match = RE2::PartialMatch(input_string,*m_alertRegex,
                            &cip,
                            &source_port);

谢谢,

更新

现在下面的代码可以工作了。

string IPRegex = "([^ \r\t:]*)";

string portRegex = "[ \r\t]*:?[ \r\t]*([0-9a-f]*)[ \r\t]*";

但是我有一个疑问,为什么“string IPRegex =”([^ \r\t:]*?)”;”不起作用? *?*?

有什么区别

输入

"123.45.34.5:8080". "123.45.34.5"

这个正则表达式 returns 8080 :

:([0-9]+)

输入

"123.45.34.5". "123.45.34.5"

这个检查字符 : 是否存在.. 因为它不存在所以 return 什么都不会 :

(\:)

为了捕获 : 左右的两个部分,您可以使用

^([^:]*)(?::([^:]+))?$

参见 demo,结果在捕获组 1 和 2 中。(正则表达式演示中的 \n 用于演示目的,因为多行模式已打开。)

关于你的问题

why string IPRegex = "([^ \r\t:]*?)"; does not work? What is the difference between *? and *?

It works,但匹配每个字符和每个单独字符之间的空字符串,因为它可以匹配空字符串。

请注意,*? 是惰性量词,匹配 0 个或多个字符,但尽可能少。它保证量化字符 class 只匹配您的模式的其余部分成功所需的尽可能多的字符。在其他正则表达式风格中,您可以使用积极的前瞻性 (?=:),但 re2 不支持环视。

有关惰性匹配的更多详细信息,请访问 rexegg.com and regular-expressions.info