亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用于驗證文件的正則表達式或函數?

用于驗證文件的正則表達式或函數?

呼啦一陣風 2023-04-26 16:44:40
我手頭有一項任務是驗證包含以下數據的文本文件的架構以下格式的 50 個條目,序列號是從 1-50 后跟一個制表符,然后是一個隨機數 n,范圍從 100<=n<=500e.g. 1 <tab> 256由于正則表達式更容易檢查文件的模式并且更易于維護我更喜歡使用正則表達式而不是一個將解析每個字符串并立即驗證的類輸出文件應該是這樣的Line 1 formatted correctlyInvalid format on line 2 (51 1000) + (Error message that can be set using a custom exception class)我的問題是,正則表達式能否強大到足以給我所需的輸出,即引發異常以正確的方式設置?我的嘗試如下public class TestOutput {    private final int MAX_LINES_TO_READ = 50;    private final String REGEX = "RAWREGEX";    public void testFile(String fileName) {        int lineCounter = 1;        try {            BufferedReader br = new BufferedReader(new FileReader(fileName));            String line = br.readLine();            while ((line != null) && (lineCounter <= MAX_LINES_TO_READ)) {                // Validate the line is formatted correctly based on regular expressions                                if (line.matches(REGEX)) {                    System.out.println("Line " + lineCounter + " formatted correctly");                }                else {                    System.out.println("Invalid format on line " + lineCounter + " (" + line + ")");                }                line = br.readLine();                lineCounter++;            }            br.close();        } catch (Exception ex) {            System.out.println("Exception occurred: " + ex.toString());        }    }    public static void main(String args[]) {        TestOutput vtf = new TestOutput();        vtf.testFile("transactions.txt");    }   }這是我的問題最佳設計應該是什么樣子(是否使用正則表達式)?如果是,使用什么正則表達式?
查看完整描述

3 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

使用此正則表達式:

String?REGEX?=?"([1-9]|[1-4]\\d|50)\t([1-4]\\d\\d|500)";

解釋...

[1-9]|[1-4]\\d|50表示“任何數字 1-50”,通過三個交替 1-9、10-49 和 50 實現。

同樣,[1-4]\\d\\d|500表示“100-500”,通過兩次交替 100-499 和 500 實現。

只有 50 行,“性能”是無關緊要的(除非你每秒執行 100 次)——選擇最易讀和理解的方法。如果您可以使用正則表達式,它通常會產生更少的代碼,并且性能足夠好。


測試代碼:

private final String REGEX = "([1-9]|[1-4]\\d|50)\\t([1-4]\\d\\d|500)";


public void testFile(String fileName) {

? ? int lineCounter = 1;

? ? try {

? ? ? ? BufferedReader br = new BufferedReader(new FileReader(fileName));

? ? ? ? String line = br.readLine();

? ? ? ? while ((line != null) && (lineCounter <= MAX_LINES_TO_READ)) {

? ? ? ? ? ? if (line.matches(REGEX)) {

? ? ? ? ? ? ? ? System.out.println("Line " + lineCounter + " formatted correctly");

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? System.out.println("Invalid format on line " + lineCounter + " (" + line + ")");

? ? ? ? ? ? }

? ? ? ? ? ? line = br.readLine();

? ? ? ? ? ? lineCounter++;

? ? ? ? }

? ? ? ? br.close();

? ? } catch (Exception ex) {

? ? ? ? System.out.println("Exception occurred: " + ex.toString());

? ? }

}

測試文件:


1? ?123

50? 346

23? 145

68? 455

1? ?535

輸出:


Line 1 formatted correctly

Line 2 formatted correctly

Line 3 formatted correctly

Invalid format on line 4 (68? ? 455)

Invalid format on line 5 (1 535)


查看完整回答
反對 回復 2023-04-26
?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

這是一個使用正則表達式的實現。匹配器為每個匹配項提供子表達式。并且這些限制是用 Java 實現的。


boolean matchLine(String line) {

    Pattern p = Pattern.compile("^(\\d+)\\t(\\d+)");

    boolean ok = false;

    try {

        Matcher m = p.matcher(line);

        int i = Integer.parseInt(m.group(1));

        int n = Integer.parseInt(m.group(2));

        ok = 1 <= i && i <= MAX_LINES_TO_READ && 100<=n && n<=500;

    } catch(NumberFormatException e){};


    return ok;

}


查看完整回答
反對 回復 2023-04-26
?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

下面只是一個快速的實現。請注意,對于這樣一個微不足道的問題,速度不是問題。如評論中所述,為數字范圍編寫正則表達式可能比僅拆分選項卡上的每一行、從字符串部分解析整數并使用 good old 檢查正確的范圍更難if。


public class SplitByTab {


    public static void main(String[] args) {

        String input = "1   123\n" + "2 456\n" + "3 789\n" + "4 234\n" + "5 345\n" + "6 890";


        for (String line : input.split("\\r?\\n")) {

            validateLine(line);

        }

    }


    private static void validateLine(String line) {

        String[] parts = line.split("\\t");

        if (parts.length != 2) {

            throw new IllegalArgumentException(String.format("line '%s' does not contain exactly one tab", line));

        }

        try {

            Integer serial = Integer.valueOf(parts[0]);

            if (serial < 0 || serial > 50) {

                throw new IllegalArgumentException(

                        String.format("the value of the serial %d is not between 0 and 50", serial));

            }

        } catch (NumberFormatException e) {

            throw new IllegalArgumentException(

                    String.format("the firt part '%s' of line '%s' is not an integer", parts[0], line));

        }

        try {

            Integer randomNumber = Integer.valueOf(parts[1]);

            if (randomNumber < 0 || randomNumber > 500) {

                throw new IllegalArgumentException(

                        String.format("the value of the random number %d is not between 0 and 500", randomNumber));

            }

        } catch (NumberFormatException e) {

            throw new IllegalArgumentException(

                    String.format("the firt part '%s' of line '%s' is not an integer", parts[0], line));

        }

    }

}

輸出:


Exception in thread "main" java.lang.IllegalArgumentException: the value of the random number 789 is not between 0 and 500



查看完整回答
反對 回復 2023-04-26
  • 3 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號