如何在Java(JDK 7)中获取字符串中指定字符或固定前缀后的文本内容?
Hey there! Let's break down how to get the text after that fixed exception prefix in Java 7 — since you've got a specific string to work with, we can use simple, reliable methods built right into the JDK.
Approach 1: Using indexOf() + substring() (Recommended for Fixed Prefixes)
This method is super efficient because we know the exact prefix, so we can skip straight to the content we need without unnecessary searching.
public class ExceptionMessageExtractor { public static void main(String[] args) { String errorString = "com.microsoft.sqlserver.jdbc.SQLServerException: User not found"; String fixedPrefix = "com.microsoft.sqlserver.jdbc.SQLServerException:"; // Quick check to make sure the prefix exists (safe even if you say it's fixed!) if (errorString.startsWith(fixedPrefix)) { // Jump past the prefix by using its length as the start index String extractedMessage = errorString.substring(fixedPrefix.length()); // Trim leading whitespace (your example has a space after the colon — this cleans it up) extractedMessage = extractedMessage.trim(); System.out.println(extractedMessage); // Output: User not found } else { // Handle edge case where the prefix is missing (adjust based on your needs) System.err.println("Expected prefix not found in the input string"); } } }
Why this works:
fixedPrefix.length()gives us the exact number of characters in the prefix. Callingsubstring()with this value starts our new string right after the prefix ends.- The optional
trim()call removes any leading whitespace (like the space after the colon in your example) to give you a clean, usable error message.
Approach 2: Using split()
If you prefer a more concise approach (though slightly less efficient for fixed prefixes), you can split the string on the prefix and grab the second part of the result.
public class ExceptionMessageExtractor { public static void main(String[] args) { String errorString = "com.microsoft.sqlserver.jdbc.SQLServerException: User not found"; String fixedPrefix = "com.microsoft.sqlserver.jdbc.SQLServerException:"; // Split into max 2 parts so we don't waste time splitting further String[] stringParts = errorString.split(fixedPrefix, 2); if (stringParts.length == 2) { String extractedMessage = stringParts[1].trim(); System.out.println(extractedMessage); // Output: User not found } else { System.err.println("Expected prefix not found in the input string"); } } }
Note:
- The
2insplit(fixedPrefix, 2)ensures we only split the string once, which is more efficient than splitting all possible occurrences (though in your case, there's only one). - Again,
trim()helps clean up any leading whitespace after the colon.
Quick JDK 7 Reminder:
Both methods use core JDK 7 features — no need for Java 8+ streams or external libraries. Always include that prefix check to avoid StringIndexOutOfBoundsException if your input ever deviates from the expected format.
内容的提问来源于stack exchange,提问作者Julian Gimenez

