我试图让用户输入一些文字,然后在该文本中搜索模式。当我不使用任何支票时,该程序工作正常。但是,我希望用户只需在文本/模式中输入字符。我是regex的新手,我尝试了以下代码:
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");
}
但程序的作用是 - 它接受文本但在接受模式时进入无限循环。 而且,如果我输入不可接受的文本输入,那么它也会进入无限循环。不确定,问题出在正则表达式还是使用扫描仪。
感谢任何帮助。
答案 0 :(得分:0)
您应该从模式中删除^
,这意味着行的开头。不确定,但我认为这只适用于所有输入的开头,然后它只是通过分隔符(默认为空格)分割,因此令牌不能发出关于行开头的信号。我认为^
在你的情况下根本没用。另请注意,您应最小化变量范围,因此您需要查看将Scanner
作为字段进行审核。