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

Java兼容正则表达式需求:匹配特定逗号、句号及非[\w,.]字符

Alright, let's craft a Java-compatible regex that meets all your requirements, including fixing the edge case with periods in strings like "e...".

First, let's restate your requirements to make sure we're aligned:

  • Capture any character that's not [\w,.], except when that character is strictly surrounded by numbers (e.g., don't capture @ in 1@2, but do capture it in 1@, @2, or a@b).
  • Capture commas and periods, except when they're directly between two numbers (e.g., don't capture the comma in 1,2 or the period in 12.32, but do capture the comma in 1, 2, the period in 23., or any period in e...).

The Java-Compatible Regex

String regex = "([^\\w,.]|[,.])(?!(?<=\\d)\\1(?=\\d))";

Breakdown of the Regex

Let's walk through each part to understand how it works:

  1. ([^\w,.]|[,.]): This captures two categories of characters:
    • [^\w,.]: Any character that isn't a word character (letters, digits, underscores), comma, or period.
    • [,.]: Any comma or period.
  2. (?!(?<=\d)\1(?=\d)): This negative lookahead filters out unwanted matches:
    • (?<=\d): Checks if the captured character is immediately preceded by a digit.
    • \1: A backreference to the character we just captured (either a non-[\w,.] char, comma, or period).
    • (?=\d): Checks if the captured character is immediately followed by a digit.
    • The (?!...) ensures we only keep matches where this "digit-surrounded" condition is not true.

Test Case Verification

Let's confirm this works against your key scenarios:

  • 1,2,3: Commas are between digits → not captured (correct).
  • 1, 2, 3: Commas are followed by spaces (not digits) → commas and spaces are captured (correct).
  • 12.32: Period is between digits → not captured (correct).
  • 23.: Period has no digit after it → captured (correct).
  • e...: Periods are preceded by a letter (not a digit) → all periods are captured (correct).
  • 1@2: @ is between digits → not captured (correct).
  • a@b: @ is between letters → captured (correct).

Java Usage Example

In Java, remember to escape backslashes properly. Here's how you'd use this regex to find matches:

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

public class RegexExample {
    public static void main(String[] args) {
        String input = "1,2,3 1, 2, 3 12.32 23. e... 1@2 a@b";
        Pattern pattern = Pattern.compile("([^\\w,.]|[,.])(?!(?<=\\d)\\1(?=\\d))");
        Matcher matcher = pattern.matcher(input);
        
        while (matcher.find()) {
            System.out.println("Captured: '" + matcher.group(1) + "'");
        }
    }
}

This code will output all the characters that meet your capture rules.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:18:38