Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading