我有一个这样的字符串;
ab cd 1234567 1234567 ef gh 1234567 1234567 ij kl - - - -
我希望输出看起来像这样;
abcd 1234567 1234567 efgh 1234567 1234567 ijkl - - - -
如何做到这一点?目前,我正在使用以下内容,但它不起作用。
result = result.trim().replaceAll("(\\w)(\\s+)([\\.,])", "");
谢谢。
发布于 2018-10-24 02:46:40
我认为这个模式对你很有效。/(?<=[a-zA-Z])\s(?=[a-zA-Z])/m
下面是一个示例代码。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(?<=[a-zA-Z])\\s(?=[a-zA-Z])";
final String string = "ab cd 1234567 1234567 ef gh 1234567 1234567 ij kl - - - -";
final String subst = "";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
发布于 2018-10-24 03:40:48
可能有一个很好的RegEx可以做到这一点,但如果你想让代码做到这一点,我可以给你一个聪明的方法来完成它。
这是未经测试的,并且是用文本编写的,所以您可能需要对其进行调整,但您已经了解了情况。
String myString = 'ab cd 1234567 1234567 ef gh 1234567 1234567 ij kl - - - -'
//break it up into array split by space
String[] chunks = myString.split(" ")
StringBuilder sb = new StringBuilder();
Int x = 0
while (x < chunks.length)
{
if(isNumeric(chunks[x])){
//if num add space back
sb.append(chunk[x]).append(" ")
}else if(x < chunks.length - 1 && !isNumeric(chunks[x + 1])){
//if it's string & next value is also a string
sb.append(chunk[x])
}else{
//if it's a string, but next is numeric, we need space
sb.append(chunk[x]).append(" ")
}
x++;
}
//convert back to string with space between letters removed
String correctedString = builder.toString().trim();
https://stackoverflow.com/questions/52955699
复制相似问题