在 java 中通过正则表达式检查用户输入时出错

Error while checking user input through regex in java

我试图让用户输入一些文本,然后在该文本中搜索模式。当我不使用任何支票时,该程序运行良好。但是,我希望用户只在 text/pattern 中输入字符。我是正则表达式的新手,我尝试了以下代码:

import java.util.Scanner;

/**
 * The following program asks user to key in some text, creates and stores a suffix table from that text, 
 * and sorts it out. Then it asks user to key in another text, referred to as pattern; 
 * and searches for that pattern in the text. 
 * If it finds even one instance of the pattern, a console message of pattern found is displayed to the user
 * If not, a message saying pattern not found is displayed.
 */

public class SearchInSuffixTable {

private static Scanner in = new Scanner( System.in );

/**
 * This is the main method. It stores the suffixes from $text into $suffixTable, 
 * calls out sortSuffixTab method to sort the table and then searches for $pattern in suffixTable using binarySearch method. 
 */

public static void main(String[] args) {

    String text, pattern;


    System.out.println("Enter the text:");
    while(!in.hasNext("^[a-zA-Z]+"))
    {
        System.out.println("inside loop");
        System.out.println("Invalid character. Only alphabets are permitted");
        in.next();
    }
    text = in.next();

    System.out.println(text);

    System.out.println("Enter the pattern to be searched:");
    while(!in.hasNext("^[a-zA-Z]+"))
    {
        System.out.println("inside pattern's loop");
        System.out.println("Invalid character. Only alphabets are permitted");
        in.next();
    }
    pattern = in.next();

    int n = text.length();

    String[] suffixTable = new String[n];

    for(int index=0; index<n; index++)
    {
        suffixTable[index] = text.substring(index);
    }

    //calling the sort function on the suffix table to sort out the elements in alphabetical order.
    sortSuffixTab(suffixTable);

    System.out.println("The Suffix Table for the text provided:");
    System.out.println("Index\tSuffix");
    for(int index=0; index<n; index++)
        System.out.println((index+1) + "\t" + suffixTable[index]);

    System.out.println("Searching for the pattern...\n");
    if(binarySearch(suffixTable, pattern, 0, n-1)) //calling the search function to search for pattern inside the text
        System.out.println("Pattern found");
    else
        System.out.println("Pattern not found");
}

但程序所做的是 - 它接受文本,但在接受模式时进入无限循环。 而且,如果我输入不可接受的文本输入,它也会在那里进入无限循环。不确定,问题是在正则表达式中还是在使用扫描仪中。

感谢任何帮助。

您应该从您的模式中删除 ^,这意味着一行的开头。不确定,但我认为这仅适用于所有输入的开头,然后它只是按分隔符(默认为空格)拆分,因此标记无法发出有关行首的信号。而且我认为 ^ 在你的情况下根本没用。另请注意,您应该 最小化变量的范围 ,因此您需要检查将 Scanner 作为字段。