相同的正则表达式搜索结果在C++和Java中有所不同

Same regex search results differ in C++ and Java

本文关键字:Java 有所不同 C++ 正则表达式 搜索结果      更新时间:2023-10-16

使用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));