I will write about the operation of a slightly complicated string
For example
a b c triple 4649 bd d op
When there was a character string
triple 4649
I don't want to trim the half-width space included in, but I want to trim the space of other characters
In other words
abc triple 4649 bddop
I want to do something like that
a b c triple 4649 bd d op
To
a b c
triple 4649
bd d op
Hold it vertically like
"a b c"When"bd d op "
Trims a half-width space,
triple 4649
Try to adopt the policy of not trimming half-width spaces
For that purpose, it is necessary to set rules regarding the decomposition and replacement of character strings, which will be explained below.
The rules for decomposing and replacing character strings are as follows.
A delimiter for listing strings'!',`, The strings you don't want to trim@Enclose in
In the above example
a b c!@ triple 4649 @!bd d op
Becomes
I tried to implement it very simply using StreamAPI
ReplaceUtil.java
package stringutil;
import java.util.stream.Stream;
public class ReplaceUtil {
public static String replacewhiteSpace(String target,String separator,String marker) {
return Stream.of(target.split(separator))
.map(s->replacer(s,marker))
.reduce((s1,s2)->s1+s2 )
.orElse("");
}
private static String replacer(String target,String marker) {
if(target.matches(String.format("%s[\\w| ].*%s", marker,marker))) {
return target.replaceAll(String.format("%s([\\w| ].*)%s", marker,marker), "$1");
}else {
return target.replaceAll(" ", "");
}
}
}
Recommended Posts