1

Consider the following strings in an array defined in Java

G1
G12
G1-G2
G23
  • If the user enters G1, then the program should return the index of G1 and G1-G2 - > [0, 2]
  • If the user enters G2, the program should return the index G1-G2 -> [2]
  • If the user enters G12, the program should return the index of G12 -> [1]
  • ...

One easy way to do that is to tokenize each array element with '-' and then use equals() for each element. That means an O(n^2) algorithm. Is there a better way to use regular expressions so that in one loop, the program searches for the pattern and use '-' as delimiting character?

0

1 Answer 1

2

Solution would be to use the following regex;

.*(?=\b{value}\b).*

so, for example if you wish to capture G1 with your requirements;

.*(?=\bG1\b).*

Where \b is being utilized, the anchor for the beginning or the end of a word, that is perfect for your requirement. More on word boundary anchor \b, here

in Java I have the following code to test;

static List<String> list = Arrays.asList("G1", "G12", "G1-G2", "G23");
public static void main(String[] args) throws Exception {
    new ArrayList<>(Arrays.asList("G1", "G12", "G2", "G23")).forEach(s -> func(s));
}

static void func(String input) {
    String regex = ".*(?=\\b" + input + "\\b).*";
    System.out.println(input + " contained in -> " 
                       + Arrays.toString(IntStream.range(0, list.size())
                                       .filter(i -> list.get(i).matches(regex))
                                       .toArray()));
}

which results in;

G1 contained in -> [0, 2]
G12 contained in -> [1]
G2 contained in -> [2]
G23 contained in -> [3]

To see the code in action, here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.