You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Perl正则转Java时遇正则语法报错问题求助

Solving the Java Regex Error When Converting Perl's Host Parsing Pattern

Let's break down why you're hitting that "Unclosed character class" error and fix it step by step.

The Root of the Problem

Perl and Java handle regex escape sequences differently, especially when it comes to string literals and character classes:

  • In Perl, you can write [^[] to match any character except [, and [^\]] to match any character except ] without extra fuss.
  • But in Java, backslashes in string literals need to be escaped (so \ becomes \\), and character class syntax has stricter rules for closing brackets.

Your original Perl regex:

m/([^[]+)\[([^\]]+)\]/

When pasted directly into a Java regex tool, the unescaped backslashes get misinterpreted. For example, [^\]] gets read as an incomplete character class ([^]) because Java sees \] as a literal ], leaving the character class unclosed.

The Fixed Java Regex

To convert this properly, you need to escape all backslashes for Java's string literal rules, and adjust the character classes to avoid ambiguity:

String hostPattern = "([^\\[]+)\\[([^\\]]+)\\]";

Let's break this down:

  • [^\\[]+: Matches one or more characters that are not [ (the \\[ escapes the literal [ inside the character class)
  • \\[: Matches the literal opening bracket [
  • [^\\]]+: Matches one or more characters that are not ] (the \\] escapes the literal ] inside the character class)
  • \\]: Matches the literal closing bracket ]

How to Use It in Java

Here's a code snippet that replicates the original Perl logic (assuming lineInfo is a Map storing your log data):

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Map;

// ...

Pattern pattern = Pattern.compile("([^\\[]+)\\[([^\\]]+)\\]");
Matcher matcher = pattern.matcher(lineInfo.get("previous_host"));

if (matcher.find()) {
    lineInfo.put("previous_host_name", matcher.group(1));
    lineInfo.put("previous_host_ip", matcher.group(2));
}

This will correctly parse strings like mail.example.com[192.168.1.100] into the hostname (mail.example.com) and IP address (192.168.1.100), just like your Perl code did.

内容的提问来源于stack exchange,提问作者MitchBroadhead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:49:19