Collapse Whitespace Runs In Text
Strip edges and collapse whitespace runs with \s+ into single spaces before equality or dedup checks, noting which characters \s does not cover.
Code
public class WhitespaceNormalizer {
// \s 只匹配六个 ASCII 空白字符(space/tab/LF/VT/FF/CR),NBSP 不在其中
static String normalize(String input) {
return input.strip().replaceAll("\\s+", " ");
}
public static void main(String[] args) {
String raw = " balance\tupdating finished \n";
System.out.println("[" + raw + "]");
System.out.println("[" + normalize(raw) + "]");
// 归一化让仅空白不同的字符串可以相等比较与去重
System.out.println(normalize("a b").equals("a b"));
}
}How it works
The code’s whole job belongs to the class WhitespaceNormalizer and the functions normalize and main.
Watch out for
- Every symbol it touches is a language built-in — nothing to fetch.
Using it
Signature: static String normalize(String input)
Launch the file; main takes over and steps through normalize.
Key statements
return input.strip().replaceAll("\\s+", " ");
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
FAQ
- How do you run Collapse Whitespace Runs In Text?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.