我正在编写程序,如果搜索模式(单词)包含任何非字母数字字符,则希望程序不循环并请求其他搜索模式。
如果单词包含字母或数字,我将布尔字设置为false,将if语句设置为true。然后是另一个if语句,如果Boolean为真,则允许程序执行。
我的逻辑必须关闭,因为如果我只是输入" /"它仍然通过搜索模式执行。搜索模式不能包含任何非字母数字字符以包含空格。我正在尝试使用正则表达式来解决这个问题。
示例有问题的输出:
Please enter a search pattern: /
Line number 1
this.a 2test/austin
^
Line number 8
ra charity Charityis 4 times a day/a.a-A
^
以下是我的适用代码:
while (again) {
boolean found = false;
System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
String wordToSearch = input.next();
if (wordToSearch.equals("EINPUT")) {
System.out.printf("%s", "Bye!");
System.exit(0);
}
Pattern p = Pattern.compile("\\W*");
Matcher m = p.matcher(wordToSearch);
if (m.find())
found = true;
String data;
int lineCount = 1;
if (found = true) {
try (FileInputStream fis =
new FileInputStream(this.inputPath.getPath())) {
File file1 = this.inputPath;
byte[] buffer2 = new byte[fis.available()];
fis.read(buffer2);
data = new String(buffer2);
Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
while (in.hasNextLine()) {
String line = in.nextLine();
Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println("Line number " + lineCount);
String stringToFile = f.findWords(line, wordToSearch);
System.out.println();
}
lineCount++;
}
}
}
}
答案 0 :(得分:2)
停止重新发明轮子。
阅读本文:Apache StringUtils,
专注于isAlpha
,
isAlphanumeric
,
和isAlphanumericSpace
其中一个可能会提供您想要的功能。
答案 1 :(得分:1)
好吧,因为没有人发布过REGEX,所以你去了:
package com.company;
public class Main {
public static void main(String[] args) {
String x = "ABCDEF123456";
String y = "ABC$DEF123456";
isValid(x);
isValid(y);
}
public static void isValid(String s){
if (s.matches("[A-Za-z0-9]*"))
System.out.println("String doesn't contain non alphanumeric characters !");
else
System.out.println("Invalid characters in string !");
}
}
答案 2 :(得分:0)
现在,发生的事情是搜索模式是否包含非字母数字字符,然后进行循环。这是因为检测到非字母数字字符时found = true
。
if(m.find())
found = true;
应该是什么:
if(!m.find())
found = true;
应该检查非字母数字字符的缺席。
此外,布尔标志可以简化为:
boolean found = !m.find();
您不需要使用if语句。
答案 3 :(得分:0)
创建一个单独的方法来调用您正在搜索的String:
public boolean isAlphanumeric(String str)
{
char[] charArray = str.toCharArray();
for(char c:charArray)
{
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
然后,在第二个try语句之前将以下if语句添加到上面的代码中。
if (isAlphanumeric(wordToSearch) == true)