gpt4 book ai didi

java - 我在 Pattern.compile() 和 .matcher() 中传递变量,但没有获得所需的输出

转载 作者:行者123 更新时间:2023-12-01 18:53:24 25 4
gpt4 key购买 nike

我编写了一个程序,要求用户提供目标字符串和要在其中搜索的模式。它的目的是找到匹配模式的位置以及它在目标字符串中出现的次数。但它始终显示未找到模式,即使目标字符串中存在该模式。我为它编写了一个函数searchPattern()

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

public class Main
{
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{

String pattern,target;
System.out.println("Enter Target String: ");
pattern = sc.nextLine();
System.out.println("Enter pattern to be searched: ");
target = sc.nextLine();
searchPattern(pattern,target);
}
public static void searchPattern(String pattern,String target)
{
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(target);
int count = 0;
//if(!m.find())return;
while (m.find())
{
count ++;
System.out.println(m.start() + "--" + m.end() + "--" + m.group());
}
if (count == 0)
System.out.println("Your pattern was not found in the target string");
else
System.out.println("Total occurrences of 'ab' are" + count);

}
}

它给出以下输出:

Enter Target String: 
ababbab
Enter pattern to be searched:
ab
Your pattern was not found in the target string

即使目标字符串中存在“ab”,为什么此代码不起作用

最佳答案

您将目标和模式存储在错误的变量中

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

public static void main(String[] args) {

String pattern, target;
System.out.println("Enter Target String: ");
target = sc.nextLine();
System.out.println("Enter pattern to be searched: ");
pattern = sc.nextLine();
searchPattern(pattern, target);
}

public static void searchPattern(String pattern, String target) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(target);
int count = 0;
while (m.find()) {
count++;
System.out.println(m.start() + "--" + m.end() + "--" + m.group());
}
if (count == 0) {
System.out.println("Your pattern was not found in the target string");
} else {
System.out.println("Total occurrences of " + pattern + " are" + count);
}
}

关于java - 我在 Pattern.compile() 和 .matcher() 中传递变量,但没有获得所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59697880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com