0

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.

Prajyod Kumar
  • 395
  • 2
  • 4
  • 15

2 Answers2

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