如何删除非字母数字字符之间的空格?例如
anti - C6 / 36 membrane antibodies D2 NS1 - P1 - specific antibodies
要
anti-C6/36 membrane antibodies D2 NS1-P1-specific antibodies
答案 0 :(得分:1)
您可以将此基于外观的正则表达式用于搜索:
(?<![\p{L}\p{N}]) +| +(?![\p{L}\p{N}])
并用空字符串替换它。
在Java中:
String repl = input.replaceAll( "(?<![\\p{L}\\p{N}]) +| +(?![\\p{L}\\p{N}])", "" );
(?<![\p{L}\p{N}]) | (?![\p{L}\p{N}])
表示如果空格后面没有字母数字或者前面没有字母数字,则匹配空格。
答案 1 :(得分:1)
(?<=\W)[ ]+|[ ]+(?=\W)
试试这个。empty string
。见。演示。
https://regex101.com/r/zB3hI5/11
对于java,它将是
(?<=\\W)[ ]+|[ ]+(?=\\W)
答案 2 :(得分:0)
尝试使用这样的正则表达式:
public static void main(String[] args) {
String s1 = "anti - C6 / 36 membrane antibodies";
String s2 = "D2 NS1 - P1 - specific antibodies";
String pattern = "\\s+(?=[^a-zA-Z0-9]+)|(?<=[^a-zA-Z0-9])\\s+";// replace all spaces either preceeded by or followed by a non-alphanumeric character
System.out.println(s1.replaceAll(pattern, ""));
System.out.println(s2.replaceAll(pattern, ""));
}
O / P:
anti-C6/36 membrane antibodies
D2 NS1-P1-specific antibodies