Java Regex如何查找String是否包含字符,但顺序不是问题
我有这样的字符串“abcdefgh”
我想检查字符串是否包含以下字符[fcb]
条件是:字符串必须包含 任何顺序的所有字符。
如何为这个写一个正则表达式。
我试过跟随正则表达式:
。* [fcb]。* —>在这种情况下,它不会检查所有字符。 如果任何一个字符匹配,它将返回true
不要使用正则表达式。 只需使用String.contains
依次测试每个字符:
in.contains("f") && in.contains("c") && in.contains("b")
你可以得到特色并对其进行排序。 之后你可以检查它是否包含.*b.*c.*f.*
。
public static boolean contains(String input) { char[] inputChars = input.toCharArray(); Arrays.sort(inputChars); String bufferInput = String.valueOf(inputChars); // Since it is sorted this will check if it simply contains `b,c and f`. return bufferInput.matches(".*b.*c.*f.*"); } public static void main(String[] args) { System.out.println(contains("abcdefgh")); System.out.println(contains("abdefgh")); }
输出:
true false
这将检查字符串中是否存在所有字母。
public class Example { public static void main(String args[]) { String stringA = "abcdefgh"; String opPattern = "(?=[^ ]*f)(?=[^ ]*c)(?=[^ ]*b)[^ ]+"; Pattern opPatternRegex = Pattern.compile(opPattern); Matcher matcher = opPatternRegex.matcher(stringA); System.out.println(matcher.find()); } }
你可以使用positive lookahead
(?=.*b)(?=.*c)(?=.*f)
不是很有效但很容易理解:
if (s.matches(".*b.*") && s.matches(".*c.*") && s.matches(".*f.*"))