简体   繁体   中英

Java Regex to count & delete spaces at beginning of a line?

Searched other questions couldn't find any results.

I've written a regex to delete the spaces from the beginning of the line, but I need to count them and have them at the beginning of the line?

scan.nextLine().replaceAll("\\s+", "").trim();

Above is the regex (it's in a while loop). I'm reading in the text in a while loop to check if there is more text and it works fine but I don't know how I can print an integer with the number of spaces removed.

If you want to count the white spaces at the beginning of a string:

String s = "  123456";
int count = s.indexOf(s.trim());

Try this: This will give you count of leading and trailing spaces.

String str = "  Hello   ";
int strCount = str.length();

For getting leading spaces:

String ltrim = str.replaceAll("^\\s+","");
System.out.println(":"+ltrim+": spaces at the beginning:" + (strCount-ltrim.length()));

For getting trailing spaces:

String rtrim = str.replaceAll("\\s+$","");
System.out.println(":"+rtrim+": spaces at the end:" + (strCount-rtrim.length()));

You can use Pattern & Matcher, this way you can get the string that matches and the lenght of it.

String pattern = "\\s+";
String str = "     Hello   ";
Matcher matcher = Pattern.compile(pattern).matcher(str);
if(matcher.find()){
    System.out.println(matcher.group().length());
    str = matcher.replaceAll("");
    System.out.println(str);
} 

Why not just do like this?

String line = scan.nextLine();
String trimmedLine = line.replaceAll("^\\s+", "");
int spacesRemoved = line.length() - trimmedLine.length();

Do like this

 public static void main(String args[]){

            String scan =" Hello World";

              String scan1= scan.replaceAll("^\\s*","");

                   int count = scan.length()-scan1.length();

            System.out.println("Number of Spaces removed at the begining"+count);

         }

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