使用java,查找来自给定范围的字母是否出现--如果字符串为真--我有如下格式的这些字符串的列表:有更多,但这里有一些示例
9-11 w: wwtxmsjwjwlw separate to: 9-11//int-int/range , w //char/letter , wwtxmsjwjwlw//string we are checking --false
5-6 g: wggghg separate to 5-6 , g , wgggghg --true
1-5 g: dxggdggb seperate to 1-5 , g , dxggdggb --true
5-13 f: lfgdplfffxffswck separate to 5-13 , f, lfgdplfffxffswck --true
6-7 z: zzzzgzzzz separate to 6-7 , z , zzzzgzzzz -- check if z is repeated 6-7 times in string zzzzgzzzz which here z is repeated 8 times so its not true --false --这些是给定字符串的示例,它们被分成三个不同的部分,它们在我放置的不同数组中共享相同的索引。问题的目的是取字母/字符事件,基本上检查给定范围int-int中的事件在字符串中是否为真,然后是cnt++,它不是真的--没有发生什么事情--cnt没有变化。-but,我想检查字母是否出现在字符串的给定范围内--如果这是有意义的。下面是我对它进行编码的尝试:
public static Scanner reader= new Scanner(System.in);
public static void main(String[] args){
int g=1000,cnt2=0;
String[] a1 = new String[g];
String[] a2 = new String[g];
String[] a3 = new String[g];
int cnt=0;
String regexp = "(?<one>\\d+-\\d+)\\s*(?<two>\\w+)\\s*:\\s*(?<three>\\w+)";
for(int i=0;i<10000;i++) {
String str = reader.nextLine();
cnt++;
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
a1[i]= matcher.group("one");
a2[i]= matcher.group("two");
a3[i]= matcher.group("three");
}
if(a3[i].matches("[a2[i]{a1[i]}")==true) {//("[a2[i]{a1[i]}") --a1[i] is error since its int-int and not int,int cause in regex range is {int, int} so how can i change that - to ,or change it so it works?
cnt2++;
}
}
System.out.println(cnt);
System.out.println(cnt2);
}cnt2应该告诉我有多少输入与这个特定字母的出现相匹配,不起作用,所以我们非常感谢您的帮助,如果有比我对数组的想法更有效的方法,请告诉我。帮助改进这个问题也会有帮助,谢谢。
发布于 2020-12-02 09:32:44
刚为有兴趣的人用以下代码解决了这个问题-
public static Scanner reader= new Scanner(System.in);
public static void main(String[] args){
int cnt2=0;
String a1="";
String a2="";
String a3="";
int cnt=0;
String regexp = "(?<one>\\d+-\\d+)\\s*(?<two>\\w+)\\s*:\\s*(?<three>\\w+)";
Pattern pattern = Pattern.compile(regexp);
String str = reader.nextLine();
while (!str.equals("-1")) {
System.out.println(str);
cnt++;
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
a1= matcher.group("one");
a2= matcher.group("two");
a3= matcher.group("three");
}
int min=Integer.parseInt( ""+ a1.split("-")[0]);
int max=Integer.parseInt( ""+ a1.split("-")[1]);
int acurences =("!"+a3+"!").split(a2).length-1;
if(acurences>=min &&acurences<=max) {
cnt2++;
}
str = reader.nextLine();
}
System.out.println(cnt);
System.out.println(cnt2);
}https://stackoverflow.com/questions/65103830
复制相似问题