I am using a pattern \s\s\s\s(.*) on a String " XYX XYQ WQHY ". So after using this pattern on this string the white spaces are trimmed.exactly starting four spaces should be removed but not the rest of white spaces.I am using this pattern in JAVA.
Asked
Active
Viewed 62 times
0
-
You need to show bit of your code with sample input/output strings. – anubhava Aug 05 '14 at 10:26
2 Answers
1
Regex to remove the first 4 spaces would be,
^\s{4}(.*)$
Java regex would be,
^\\s{4}(.*)$
Replacement string:
$1
Java code would be,
String s = " XYX XYQ WQHY ";
String m = s.replaceAll("^\\s{4}(.*)$", "$1");
System.out.println(m); //=>XYX XYQ WQHY
Like anubhava said in his comment, you could replaceFirst function.
String s = " XYX XYQ WQHY ";
String m = s.replaceFirst(" {4}", "");
System.out.println(m);
It removes the exact four spaces at the start.

Avinash Raj
- 172,303
- 28
- 230
- 274
1
would this do?
newString = yourString.replaceAll("^ {4}","");
if you want to remove the leading 4 spaces or Tabs:
newString = yourString.replaceAll("^\\s{4}","");

Kent
- 189,393
- 32
- 233
- 301
-
2
-
@anubhava yea, the replaceFirst is better for this replacement. mine (replaceAll) costs one more `find()` than the replaceFirst. – Kent Aug 05 '14 at 10:35