简体   繁体   中英

Why java String.replaceAll regex removes part of string which it shouldn't?

I want to use regex to remove all characters that are not in range from input string. Here is my code:

System.out.print("Input: ");
Scanner scan = new Scanner(System.in);
String input = scan.next();
scan.close();
String formattedInput = input.replaceAll("[^a-zA-Z]", "");
System.out.println(formattedInput);

Here how it works:

input: test,test test
testtest

Why it removed 3rd occurence of test? I wanted him to remove only "," and " " in that particular case.

It's because you used a scanner and calling scan.next only picked up test,test .

A nice way to debug these kinds of things would be to do a System.out.println(input) just before your statement that calls replaceAll .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM