Reputation: 19517
This is my string.. how can i remove the spaces using reg exp in java
08h03 Data1 Data2 Data3 Data4 5
Is there any way i already tried replace(" ","");
Upvotes: 0
Views: 1597
Reputation: 63698
Use replaceAll() Method.
String s = "08h03 Data1 Data2 Data3 Data4 5 ";
s = s.replaceAll("\\s", "");
Upvotes: 2
Reputation: 170178
You probably didn't reassign the string. Try:
String s = "08h03 Data1 Data2 Data3 Data4 5";
s = s.replace(" ", "");
Note that String.replace(...)
does not take a regex string as parameter: just a plain string.
This will remove all spaces from your string, which is an odd requirement, if you ask me. Perhaps you want to split the input? This can be done like this:
String[] tokens = s.split("\\s+"); // `\\s+` matches one or more white space characters
// tokens == ["08h03", "Data1", "Data2", "Data3", "Data4", "5"]
or maybe even replace 2 or more spaces with a single one? This can be done like this:
s = s.replaceAll("\\s{2,}", " "); // `\\s{2,}` matches two or more white space characters
// s == "08h03 Data1 Data2 Data3 Data4 5"
Upvotes: 8