如何使用Guava库从字符串提取独立数字序列(非正则方法)
Extracting Independent Digit Sequences with Guava
Got it, let's fix this up using only Google Guava! Your current code using CharMatcher.JAVA_DIGIT.retainFrom() works for grabbing all digits, but it concatenates them into one big string—we need to keep each separate digit sequence intact instead.
Solution Code
Here's how to split the original string into distinct digit sequences using Guava's Splitter and CharMatcher together:
import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import java.util.List; import java.util.Arrays; public class DigitSequenceExtractor { public static void main(String[] args) { String message = "Hello Your Account NO 295093491783 is been deducted by 17820.if you did not receive the Ack call 9897123456"; // Split the string using non-digit characters as separators, filter out empty strings List<String> digitSequences = Splitter.on(CharMatcher.JAVA_DIGIT.negate()) .omitEmptyStrings() .splitToList(message); // Convert the List to a String array as requested String[] result = digitSequences.toArray(new String[0]); // Print to verify System.out.println(Arrays.toString(result)); // Output: [295093491783, 17820, 9897123456] } }
How It Works
Let's break down the key parts:
Splitter.on(CharMatcher.JAVA_DIGIT.negate()): This tells Guava to split the input string every time it encounters a non-digit character (sincenegate()flips the matcher to match everything that isn't a digit)..omitEmptyStrings(): When there are consecutive non-digit characters (like spaces and punctuation next to each other), splitting would create empty strings—this method filters those out so we only get valid digit sequences..splitToList(): Converts the split results into aList<String>, which we then convert to aString[]usingtoArray()to match your desired output format.
This approach stays strictly within Guava's utilities and gives you exactly the separate digit sequences you need.
内容的提问来源于stack exchange,提问作者Prakhar Nigam




