0

I create a regular expression using StringBuilder that matches any string containing all characters in the string (or so I think).

StringBuilder myRegex = new StringBuilder("");
for (char c: myCharArray) {
  myRegex.append(String.format("?=.*%c", c));
}

I believe this should match the following kind of string:

char [] myCharArray = {'a', 's', 'e'};
String fruits = "Apples Bananas and Grapes";

But I get the following error:

java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0 ?=.*a?=.*s?=.*e
Bahram Ardalan
  • 280
  • 3
  • 11
Anthony O
  • 622
  • 7
  • 26
  • 1
    This looks like far far away from the solution to what I think you want to do. Are you trying to check if a string has all the letters you need? For example, array is {a,e,i,o,u} so "This" matches and "Ths" does not match. Yes? – Bahram Ardalan Nov 10 '19 at 21:34
  • yes, that is what I am trying to accomplish – Anthony O Nov 10 '19 at 21:35

1 Answers1

0

I guess, you're trying to build,

(?=.*a)(?=.*s)(?=.*e)

for the full expression of,

^(?=.*s)(?=.*e)(?=.*a).*$

which,

myRegex.append(String.format("(?=.*%c)", c));

may partially work.


Being said that, a positive lookahead for each char is not really efficient or the best idea here, because each one is an O(N) time complexity.


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Test

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


public class RegularExpression{

    public static void main(String[] args){


        final String regex = "^(?=.*s)(?=.*e)(?=.*a).*$";
        final String string = "Apples Bananas and Grapes\n"
             + "Some String that doeS not have A lower S or E or A";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
        }

    }
}

Output

 Full match: Apples Bananas and Grapes
Emma
  • 27,428
  • 11
  • 44
  • 69