正则表达式匹配指定字符或字符串末尾的匹配问题咨询
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:
- Replace the fixed
\\;with(?:\\;|$)— this uses a non-capturing group to match either a semicolon or the string end anchor ($). - 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...andmy string...groups preserve your original case-sensitive matching requirement.
Test Output
When run against your example input, this will match all three segments:
MY STRING content1 \n content1;my string content2 \n \n content2;my string content3 content3 \n content3
内容的提问来源于stack exchange,提问作者Tom Shir
相关产品推荐
相关产品推荐

