How to make a regex capture a large variation of a term? (HOUSE, House)

Asked

Viewed 89 times

1

It is as follows: since it has a term that I wish to capture, for example, "HOUSE", how to make a regex to capture many variations of this word, example:

House, House, House, House, House, House...

I know there’s

(House|House|House|House|House|House)

but see that for this it is necessary that I write all the existing variations of the word, which would be 16 for "HOUSE". Depending on the word, this would become a Herculean task. The regex have a mechanism to make our lives easier?

  • 4

    Could it not be so (?i)(house) ? with the (?i) meaning Case-Insensitive, so it would match in all possible combinations of "house "

2 answers

5


You can use:

/(casa)/ig

Explanation:

  • (word): Character capture group literally
  • /i: modifier for insensitive
  • /g: modifier to global

For Java, as @Aronlinhares commented, it should be:

(?i)(casa)

Regexr: http://regexr.com/3ev1q

2

You can use the flag of CASE_INSENSITIVE. Behold this example working on ideone:

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("casa", Pattern.CASE_INSENSITIVE);
        System.out.println(p.matcher("Casa").matches());
        System.out.println(p.matcher("CaSa").matches());
        System.out.println(p.matcher("CAsA").matches());
        System.out.println(p.matcher("casa").matches());
        System.out.println(p.matcher("CaSA").matches());
        System.out.println(p.matcher("Sopa").matches());
        System.out.println(p.matcher("Carro").matches());
        System.out.println(p.matcher("Verde").matches());
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.