Home > Software design >  How to build regex to match values if they exists
How to build regex to match values if they exists

Time:02-12

I have a requirement to match the complete string if some part of value exists or not

For example :- Here are the list of strings that should be matched

en.key.value fr.key.value es.key.value pt.key.value key.value

So, length of string before first . can only be >=2.

Below are some values which should not be accepted

.key.value z.key.value

Could someone please help ? Thanks in advance

CodePudding user response:

You could use the following regex : /[a-z]{2,}\.[a-z] \.[a-z] /g

[a-z]{2,} matches 2 or more repetitions of characters in the range between a and z.

\. matches the dot character.

[a-z] matches 1 or more repetitions of characters between a and z.

let regex = /[a-z]{2,}\.[a-z] \.[a-z] /g;

console.log(regex.test("fr.key.value"));
console.log(regex.test("z.key.value"));

Regex101.

CodePudding user response:

^[^.]{2,}\.. $

Matches

en.key.value
fr.key.value
es.key.value
pt.key.value
key.value

Does not match

.key.value
z.key.value

See yourself: Regexr.com

CodePudding user response:

You don't need to use regular expressions. You can split the string on the dots and check the length of the first part.

String[] strings = {"en.key.value",
                    "fr.key.value",
                    "es.key.value",
                    "pt.key.value",
                    "key.value",
                    ".key.value",
                    "z.key.value"};
for (String string : strings) {
    String[] parts = string.split("\\.");
    System.out.printf("[%b] %s%n", (parts[0].length() >= 2), string);
}

Above code produces following output.

[true] en.key.value
[true] fr.key.value
[true] es.key.value
[true] pt.key.value
[true] key.value
[false] .key.value
[false] z.key.value

However, if you insist on using regular expressions, consider the following.

String[] strings = {"en.key.value",
                    "fr.key.value",
                    "es.key.value",
                    "pt.key.value",
                    "key.value",
                    ".key.value",
                    "z.key.value"};
Pattern pattern = Pattern.compile("^[a-z]{2,}\\.");
for (String string : strings) {
    Matcher matcher = pattern.matcher(string);
    System.out.printf("[%b] %s%n", matcher.find(), string);
}

Explanation of regular expression ^[a-z]{2,}\\.

  • ^ start of string
  • [a-z] any lower-case letter of the English alphabet
  • {2,} two or more occurrences of the preceding
  • \\. literal dot

In other words, the above pattern matches strings that start with two or more lower-case characters followed by a single dot.

  • Related