如何使用 Java 正則表示式(RegEx)刪除空格
正則表示式“\s”匹配字串中的空格。replaceAll() 方法接受一個字串和一個正則表示式,並將匹配到的字元替換為給定的字串。要刪除輸入字串中的所有空格,可以使用上述正則表示式和空字串作為輸入,呼叫其 replaceAll() 方法。
示例 1
public class RemovingWhiteSpaces { public static void main( String args[] ) { String input = "Hi welcome to tutorialspoint"; String regex = "\s"; String result = input.replaceAll(regex, ""); System.out.println("Result: "+result); } }
輸出
Result: Hiwelcometotutorialspoint
示例 2
類似,appendReplacement() 方法接受一個字串緩衝和一個替換字串,將匹配到的字元和給定的替換字串一起追加到字串緩衝中。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemovingWhiteSpaces { public static void main( String args[] ) { Scanner sc = new Scanner(System.in); System.out.println("Enter input string: "); String input = sc.nextLine(); String regex = "\s"; String constants = ""; System.out.println("Input string: \n"+input); //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); //Creating an empty string buffer StringBuffer sb = new StringBuffer(); while (matcher.find()) { constants = constants+matcher.group(); matcher.appendReplacement(sb, ""); } matcher.appendTail(sb); System.out.println("Result: \n"+ sb.toString()+constants ); } }
輸出
Enter input string: this is a sample text with white spaces Input string: this is a sample text with white spaces Result: thisisasampletextwithwhitespaces
示例 3
public class Just { public static void main(String args[]) { String input = "This is a sample text with spaces"; String str[] = input.split(" "); String result = ""; for(int i=0; i<str.length; i++) { result = result+str[i]; } System.out.println("Result: "+result); } }
輸出
Result: Thisisasampletextwithspaces
廣告