簡體   English   中英

Java正則表達式計算和刪除行首的空格?

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

搜索其他問題沒有找到任何結果。

我寫了一個正則表達式來刪除行首的空格,但我需要計算它們並將它們放在行首?

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

上面是正則表達式(它在一個 while 循環中)。 我在 while 循環中閱讀文本以檢查是否有更多文本並且它工作正常但我不知道如何打印刪除空格數的整數。

如果要計算字符串開頭的空格數:

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

試試這個:這將為您提供前導和尾隨空格的計數。

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

為了獲得領先的空間:

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

獲取尾隨空格:

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

您可以使用 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);
} 

為什么不這樣做呢?

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

這樣做

 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