将Perl正则转Java时遇正则语法报错问题求助
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

