簡體   English   中英

每個newLine的字符驗證

[英]Character validation for each newLine

我試圖找到一種方法來驗證是否從“ srcFile”讀取的每一行都以字母字符開頭。 我嘗試使用Character.isLetter()方法,但它抱怨將行聲明為String而不是char數組...從我的想法來看,String是字符數組,但顯然isLetter()在那樣。 我想知道我可以使用什么方法。 我想從srcFile過濾數據並將其放置在HashMap和Vector中,但是我首先需要找到一種有效且干凈的方法來確定行是否以字母字符開頭。 我還考慮過使用String.contains(),因為我知道我要查找的是特定的char序列,但是它將變得更加冗長和不必要的編碼方式,這也使我的程序不那么通用,我想在一定程度上。

    try {
        Scanner myScanner = new Scanner(srcFile);
        // Why not declare line outside while loop 
        // and write cond. as (line = myScan... != null) ?
        while (myScanner.hasNextLine()) {
            String line = myScanner.nextLine();
            //System.out.println(line);

            if (Character.IsLetter(line[0])) {

            }
        }
        myScanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

其余條件如下:

                //if first char start with a aplha char, move to the ticket list
                if (Char.IsLetter(line[0]))
                {
                    ticket t = new ticket();
                    t.parseLine(line);
                    //logger.Debug(line);

                    tickets.Add(t);
                }
                else
                {
                    sbPeople sbuPeople = new sbPeople();
                    sbuPeople.parseLine(line);

要獲取字符串中的第一個字符,請使用line.charAt(0) 僅數組使用[]進行索引,而字符串不是數組。

您也可以使用正則表達式。 例如:

String line = myScanner.nextLine();
if (line.matches("^\\p{Alpha}.*$")) {
    System.out.printf("Starts with an alphabetic character: %s%n", line);
    ...
} else {
    ...
}

正則表達式中每個項目的說明:

NODE                     EXPLANATION
---------------------------------------------------------------------
  ^                        the beginning of the string
---------------------------------------------------------------------
  \p{Alpha}                any character of: letters
---------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
---------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM