首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用正则表达式只删除单词之间的空格,而不是数字或特殊字符?

如何使用正则表达式只删除单词之间的空格,而不是数字或特殊字符?
EN

Stack Overflow用户
提问于 2018-10-24 02:31:58
回答 2查看 65关注 0票数 1

我有一个这样的字符串;

代码语言:javascript
复制
ab cd 1234567 1234567 ef gh 1234567 1234567 ij kl - - - -

我希望输出看起来像这样;

代码语言:javascript
复制
abcd 1234567 1234567 efgh 1234567 1234567 ijkl - - - -

如何做到这一点?目前,我正在使用以下内容,但它不起作用。

代码语言:javascript
复制
result = result.trim().replaceAll("(\\w)(\\s+)([\\.,])", "");

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2018-10-24 02:46:40

我认为这个模式对你很有效。/(?<=[a-zA-Z])\s(?=[a-zA-Z])/m

下面是一个示例代码。

代码语言:javascript
复制
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);
票数 1
EN

Stack Overflow用户

发布于 2018-10-24 03:40:48

可能有一个很好的RegEx可以做到这一点,但如果你想让代码做到这一点,我可以给你一个聪明的方法来完成它。

这是未经测试的,并且是用文本编写的,所以您可能需要对其进行调整,但您已经了解了情况。

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52955699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档