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

正则表达式匹配指定字符或字符串末尾的匹配问题咨询

Fixing Regex to Match Content Ending with ; or String End

Got it, let's work through why your regex isn't picking up that last segment and fix it!

The Issue with Your Current Regex

Your current pattern only targets content that ends with a semicolon (;), but it doesn't account for cases where the content runs all the way to the end of the string (no trailing semicolon). That's exactly why the third segment gets left out.

The Fix: Add the String End Anchor

We need to adjust the regex to accept either a semicolon or the end of the string as the termination point. Here's how to tweak it:

  1. Replace the fixed \\; with (?:\\;|$) — this uses a non-capturing group to match either a semicolon or the string end anchor ($).
  2. Swap .*? for [\s\S]*? if your content includes line breaks (like in your example). The default .* doesn't match newlines, so [\s\S] ensures we capture all characters (including line breaks) in a non-greedy way.

Updated Code Example

String inputStr = "MY STRING content1 \n content1; my string content2 \n \n content2; my string content3 content3 \n content3";
Pattern adjustedPattern = Pattern.compile("(MY STRING([\\s\\S]*?)(?:\\;|$))|(my string([\\s\\S]*?)(?:\\;|$))");
Matcher matcher = adjustedPattern.matcher(inputStr);

while (matcher.find()) {
    // Extract the full matched segment
    String matchedContent = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
    System.out.println("Matched segment: " + matchedContent);
}

Breakdown of the Updated Regex

  • (?:\\;|$): Non-capturing group that matches either a semicolon or the end of the string. The ?: avoids creating an extra capture group we don't need.
  • [\s\S]*?: Non-greedy match of any character (including newlines) — this stops as soon as it hits a semicolon or the string end, preventing over-matching later content.
  • The separate MY STRING... and my string... groups preserve your original case-sensitive matching requirement.

Test Output

When run against your example input, this will match all three segments:

  1. MY STRING content1 \n content1;
  2. my string content2 \n \n content2;
  3. my string content3 content3 \n content3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:37:34