简体   繁体   English

Java正则表达式计算和删除行首的空格?

[英]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).上面是正则表达式(它在一个 while 循环中)。 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.我在 while 循环中阅读文本以检查是否有更多文本并且它工作正常但我不知道如何打印删除空格数的整数。

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.您可以使用 Pattern & Matcher,这样您就可以获得匹配的字符串及其长度。

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);

         }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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