用于有条件删除空白的Java模式正则表达式

用于有条件删除空白的Java模式正则表达式,java,regex,Java,Regex,我已经寻找了几个小时的答案,但仍然没有任何东西可以解决具体的编程难题。这既不是为了上学也不是为了工作。我正在开发一个应用程序,它需要基于正则表达式执行预定义的数据清理任务。我遇到的一个具体表达式是删除单词和数字之间的空白字符。以下是要求示例: word 123 ==> word123 123 word ==> 123word world 123 wide ==> word123wide world wide 123 ==&

我已经寻找了几个小时的答案,但仍然没有任何东西可以解决具体的编程难题。这既不是为了上学也不是为了工作。我正在开发一个应用程序,它需要基于正则表达式执行预定义的数据清理任务。我遇到的一个具体表达式是删除单词和数字之间的空白字符。以下是要求示例:

word 123           ==> word123
123 word           ==> 123word
world 123 wide     ==> word123wide
world wide 123     ==> world wide123
world wide 123 456 ==> world wide123 456
RegEx lookaround似乎是正确的方法,但仍然无法找出如何将表达式应用于具有2个以上单词块的短语


提前感谢。

在两个
模式
之间结合使用lookarounds和altrance,如下所示:

//                | preceded by digit
//                |      | one whitespace
//                |      |   | followed by non-digit
//                |      |   |      | OR
//                |      |   |      | | preceded by non-digit
//                |      |   |      | |      | one whitespace
//                |      |   |      | |      |   | followed by digit
String pattern = "(?<=\\d)\\s(?=\\D)|(?<=\\D)\\s(?=\\d)";
// test Strings
String test0 = "word 123";
String test1 = "123 word";
String test2 = "world 123 wide";
String test3 = "world wide 123";
String test4 = "world wide 123 456";
// testing output: replace all found matches
// (e.g. one per String in this case)
// with empty
System.out.println(test0.replaceAll(pattern, ""));
System.out.println(test1.replaceAll(pattern, ""));
System.out.println(test2.replaceAll(pattern, ""));
System.out.println(test3.replaceAll(pattern, ""));
System.out.println(test4.replaceAll(pattern, ""));

+1但我可能会使用
\\s+
而不仅仅是
\\s
:“空白”通常指任意数量的空白characters@Mena-真正的正则表达式wizard@Bohemian说得好。我在我的评论中添加了“一个空格”,但它很容易被任意数量的空格所取代:)喜欢“下拉”助手的解释。这很快!现在我知道为什么我似乎不能使它适用于超过2个词块的短语。我错过了第二个环顾四周的表情。非常感谢你。
word123
123word
world123wide
world wide123
world wide123 456