2016-03-14 52 views
1

这个正则表达式适用于单词变量,但它从定义变量中删除所有不需要的空白。无法理解原因。正则表达式只保留字母和空格?

String word = "cheese[1]" 

String definition = "[:the quality of being too obviously sentimental]" 

String regex = "[^A-Za-z]+";  // how to get it to exclude whitespace? 

finaldefinition = finaldefinition.replaceAll(regex,"") 

输出:

字=奶酪

定义= thequalityofbeingtooobviouslysentimental

期望的结果:

字=奶酪

定义=的过于明显的感伤

感谢您的时间质量。

+0

“'[^ A-ZA-Z] + “' –

+0

或者'[^ A-Za-z \ s] +'如果你想保留标签和其他形式的空格。 – Evert

+0

哈哈谢谢。是这么简单吧? /捂脸 –

回答

0

您是否正在寻找?

public static void main(String[] args) {   
    String[] strs = new String[] {"cheese[1]", "[:the quality of being too obviously sentimental]"}; 
    for (String m: strs){ 
     System.out.println(m.replaceAll("[^a-zA-Z ]", ""));  
} 

输出:

cheese 
the quality of being too obviously sentimental 
0

您可以使用[^A-Za-z ]+为:

  • 任何字符,除了
    • captial字母
    • 小写字母
    • 空白

或者[^A-Za-z\s]+为:

  • 任何字符,除了
    • captial字母
    • 小写字母
    • 个空格(空格,制表符,换行符)

第三种选择:更换\s第一,使标签和linebraks将获得空白

相关问题