相同的正则表达式搜索结果在C++和Java中有所不同
Same regex search results differ in C++ and Java
使用C++和Java实用程序匹配器输出,获得的结果不同。
在C++中,我使用regex的方式如下:
#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';
由于有两个组,即第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中解决这段代码时面临循环中的问题
- 尝试用java代码编译和运行c++代码
- 在这种情况下,java对象是否可以调用本机函数
- GCC和Clang在与__builtin_constant_p相关的static_assert方面有所不同
- 在java中读取c++字节的位字段
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 使用已使用 java 编码的 openssl 解码数据
- SWIG Java 在使用 -DSWIGWORDSIZE64 时将int64_t转换为 jlong
- Android Java USB for native cpp
- 在由Sublime文本3编译后在cmd上显示Java程序输出
- C++ equivalent to Java Map getOrDefault?
- C++ 中的 Java 样式枚举
- 是否有技术原因阻止 Java 中的 final C++ 像 const 一样严格?
- 加密在 Windows、C++ 和 Java 中传输中的数据
- Java从C++回调到C++回调
- 在 c++ 中模拟输入并在 JAVA 中读取它?
- 用C++包装 Java 库 (JNI)
- 使用 TreeSet Java 对反转进行计数
- 相同的正则表达式搜索结果在C++和Java中有所不同
- Java和c++中重载方法的继承在基本方式上有所不同