匹配字面字符:
示例:a 匹配单个字母 “a”。
使用特殊字符:
示例:
\d: \d{3} 可以匹配 “123” 中的数字部分。
\w: \w+ 可以匹配 “hello123” 中的字母和数字部分。
\s: \s+ 可以匹配 “Hello World” 中的空格。

字符类:
示例:
[abc]: [abc] 匹配 “a”、“b” 或 “c” 中的任意一个字符。
[a-z]: [a-z]+ 可以匹配 “hello” 中的小写字母。
[0-9]: [0-9]{2} 可以匹配 “12” 中的数字。
[^abc]: [^abc] 匹配除了 “a”、“b” 和 “c” 之外的任意字符。
量词:
示例:
: \d 匹配任意数量的数字,包括零个。
+: \d+ 匹配至少一个数字。
?: \w? 匹配零个或一个字母或数字。
{n}: \d{3} 匹配恰好三个数字。
{n,}: \d{3,} 匹配至少三个数字。
{n,m}: \d{2,5} 匹配两到五个数字。

边界:
示例:
^: ^hello 匹配以 “hello” 开头的字符串。
:world: world:world 匹配以 “world” 结尾的字符串。
\b: \bword\b 匹配 “word” 作为单独的单词。

分组和捕获:
示例:(\d{3})-(\d{3})-(\d{4}) 可以匹配并捕获美国电话号码格式,如 “555-123-4567” 中的区号、前缀和行号

#include
#include
#include

std::string extractIPAddress(const std::string& input) {
// 定义 IP 地址的正则表达式
std::regex ipRegex(R"(ip address (\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b))");

// 在输入字符串中搜索匹配的 IP 地址
std::smatch match;
if (std::regex_search(input, match, ipRegex)) {
    // 如果找到匹配项,返回第一个匹配的 IP 地址
    return match[1]; // 使用 match[1] 来获取括号中的子表达式匹配结果
} else {
    // 如果未找到匹配项,返回空字符串或者其他适当的值
    return "";
}

}

int main() {
std::string input = “ip address 192.168.1.253 Subnet mask 255.255.255.0”;

// 提取字符串中的 IP 地址
std::string ipAddress = extractIPAddress(input);

if (!ipAddress.empty()) {
    std::cout << "Extracted IP address: " << ipAddress << std::endl;
} else {
    std::cout << "No IP address found in the input string." << std::endl;
}

return 0;

}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐