Java regex doesn't contain char and if it does, then it doesn't match string

I’m trying to write a simple Java regex that matches the next combination:

  • The string contains only some of these characters: [A-ZÑÁÀÂÉÈÊÍÌÎÓÒÔÚÙÛºª \\-]
  • If it does contain a middle dot, it has to contain exactly L·L

The next strings are valid:

  • ABCL·LGG
  • ABCL
  • BCC

The next strings aren’t valid:

  • AALL·
  • A·LLL
  • ·LL

How do I add the ‘L·L’ exception to the list?

>Solution :

I would use a capturing group with 2 alternatives (separated by |). See the demo at Regex101.

^([A-ZÑÁÀÂÉÈÊÍÌÎÓÒÔÚÙÛºª \\-]+|.+L·L.+)$
^                                            start of the string
 (                             |       )     2 alternatives capturing group
  [A-ZÑÁÀÂÉÈÊÍÌÎÓÒÔÚÙÛºª \\-]               a defined set of characters
                              +              ... at least a single character
                                .+L·L.+      anything between L·L
                                        $    end of the string

A simple test in Java (mind the escaping of certain characters):

var p = Pattern.compile("^([A-ZÑÁÀÂÉÈÊÍÌÎÓÒÔÚÙÛºª \\\\-]+|.+L·L.+)$");
Stream.of("ABCL·LGG", "AALL·", "A·LLL", "·LL")
      .forEach(s -> System.out.println(s + " -> " + p.matcher(s).matches()));
ABCL·LGG -> true
AALL· -> false
A·LLL -> false
·LL -> false

Leave a Reply