我有一个字符池,我想使用正则表达式匹配所有这些字符的字谜或这些字符的子集的单词。
示例:给定字符串“ACNE”,正则表达式应该给我这些结果:
- 痤疮 [T]
- 塞纳 [T]
- 不能]
- 卡恩 [F]
- 佳能 [F]
我已经尝试过这个解决方案/b[acne]{1,4}/b
,但它接受多个重复的单个字符。我能做些什么来最多一次获取每个字符?
“痤疮”这个词的子变位词是那些
acne
a
超过一次c
超过一次n
超过一次e
超过一次将其编译为正则表达式:
^(?!.*a.*a)(?!.*c.*c)(?!.*n.*n)(?!.*e.*e)[acne]*$
测试:正则表达式
或者,由于“acne”不包含不止一次的任何字母,“acne”这个词的子变位词是
acne
将其编译为正则表达式:
^(?!.*(.).*\1)[acne]*$
测试:正则表达式
注意:单词“magmoid”的子字谜可以匹配为
^(?!.*([agoid]).*\1)(?!(.*m){3})[magoid]*$
(不包含任何agoid
超过一次,也不包含m
超过两次)
使用正则表达式在给定字符串中查找单词的字谜数量的代码
Fork 下面的存储库,用于 Java、DataStructure、算法和公司面试问题实践。请随时为存储库做出贡献
package com.techsqually.java.library.util.regularexpression;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class anagramStrings {
public static void main(String[] args) {
int count = findAnagramsInAGivenStrings("arpan","Hi arpan Aarpn we are testing rapan rranp anagram");
System.out.println(count);
}
/**
* <p> Use to find the number of anagrams of a word in a Given String</p>
* @param : word : is the word for which you want to find the anagrams
* @param : givenString : is the string in which you want to find the anagrams of word given
* @return : total number of anagrams of the word passed
*
* all words in which each character count is same but their order can be different
* e.g arpan and rapan are anagrams
*
* @output of above given example is 3, "arpan" , "Aarpn" and rapan are anagrams of arpan
* */
public static int findAnagramsInAGivenStrings(String word, String givenString){
word = word.toLowerCase();
givenString = givenString.toLowerCase();
HashMap<String,Integer> numberOfAnnagrams = new HashMap<>();
Matcher matcher = Pattern.compile("[" + word + "]{" + word.length() + "}").matcher(givenString);
int count = 0;
while (matcher.find()){
char[] matchWordArray = matcher.group().toCharArray();
char[] givenWordArray = word.toCharArray();
Arrays.sort(matchWordArray);
Arrays.sort(givenWordArray);
if (Arrays.equals(matchWordArray,givenWordArray)) count++;
}
return count;
}
}