簡體   English   中英

初學者正則表達式Java

[英]Beginner Regular Expressions Java

我想寫一個正則表達式,它將與名稱的幾種變體/常用用法之一匹配。

我需要接受用戶輸入,然后驗證輸入是否與列出的變體之一匹配。 如果存在匹配項,我需要輸出存在匹配項,否則,我應該輸出輸入不是匹配項。

這是我到目前為止的內容:

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExMyName {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("Name: Daimon");
        System.out.println("Common Usages: Daimon, Daimo, Dai, daimon, daimo, DAIMON");
        System.out.println("Enter any of the variations listed only: ");

        //*** HELP REQUIRED WITH PATTERN BELOW - pat
        Pattern pat = Pattern.compile();
        Matcher match = pat.matcher(scan.nextLine());


        //***HELP REQUIRED WITH FIND BELOW
        if (match.find()){
            System.out.println("*** You entered a valid name ***");
        }else{
            System.out.println("*** You entered an invalid name ***");
        }




    }
}

我需要一些幫助來構建模式或接收有關可以完成相同任務的替代方法的建議。

謝謝。

這種模式將匹配任何字符串的DaimonDaimoDaidaimondaimoDAIMON

Pattern pattern = Pattern.compile("^([dD]aimon?|DAIMON|Dai)$");

或稍大一些的模式看起來像這樣

Pattern pattern = Pattern.compile("^dai(mon?)?$",Pattern.CASE_INSENSITIVE);

在您描述的情況下,我不使用正則表達式,而寧願存儲名稱的可能變體,例如,在List中僅使用簡單的contains即可驗證輸入。

List<String> daimons = Arrays.asList("Daimon", "Daimo", "Dai", "daimon", "daimo", "DAIMON");

對於您的示例,我沒有真正看到正則表達式的功能。 如果我看不到您的解決方案,則可能是類似的情況:

公共類RegExMyName {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    List<String> daimons = Arrays.asList("Daimon", "Daimo", "Dai", "daimon", "daimo", "DAIMON");
    StringBuilder diamonCommonUsage = new StringBuilder();
    for(String daimonVariations : daimons) {
      diamonCommonUsage.append(daimonVariations);
      diamonCommonUsage.append(", "); //+ remove the last ","
    }        

    System.out.println("Name: Daimon");
    System.out.println("Common Usages: " + diamonCommonUsage.toString());
    System.out.println("Enter any of the variations listed only: ");

    if (match.find(daimons.contains(scan.nextLine()))){
        System.out.println("*** You entered a valid name ***");
    }else{
        System.out.println("*** You entered an invalid name ***");
    }
}

}

暫無
暫無

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

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