使用 C++ 和 Java 实用程序匹配器输出得到的结果不同。
在 C++ 中,我按以下方式使用正则表达式:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string lines[] = {"https12e345d"};
std::regex color_regex("^(?:http|https)([A-Fa-f0-9].*)$");
for (const auto &line : lines) {
std::cout << line << ": "
<< std::regex_search(line, color_regex) << '\n';
}
std::smatch color_match;
for (const auto &line : lines) {
std::regex_search(line, color_match, color_regex);
std::cout << "matches for '" << line << "'\n";
for (size_t i = 0; i < color_match.size(); ++i)
std::cout << i << ": " << color_match[i] << '\n';
}
}
使用 Java:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static final String EXAMPLE_TEST = "https12e345d";
public static void main (String[] args) throws java.lang.Exception
{
Pattern pattern = Pattern.compile("^(?:http|https)([A-Fa-f0-9].*)$");
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
// check all occurance
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
}
}
C++ 输出是:
https12e345d
12e345d
Java 输出是:
https12e345d
正则表达式有问题吗?
最佳答案
输出的不同之处在于,在 C++ 代码中,您使用
迭代捕获的组for (size_t i = 0; i < color_match.size(); ++i)
std::cout << i << ": " << color_match[i] << '\n';
因为有 2 组,第 0 组(整个匹配的文本)和第 1 组(用 (...)
捕获的组)你在输出中有两个字符串。
使用 Java 代码,
while (matcher.find()) {
System.out.println(matcher.group());
}
您迭代匹配项(只有 1 个匹配项,因此,您只有 1 个输出)并打印出整个匹配的文本(在 C++ 中,它是 color_match[0]
)。如果您想要与 C++ 中相同的输出,在 Java 代码中,添加
System.out.println(matcher.group(1));
关于java - 相同的正则表达式搜索结果在 C++ 和 Java 中不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33416892/