2

I have an input string and I want to use regex to check if this string has = and $, e.g:

Input:

name=alice$name=peter$name=angelina

Output: true

Input:

name=alicename=peter$name=angelina

Output: false

My regex does't work:

Pattern pattern = Pattern.compile("([a-z]*=[0-9]*$])*");
Matcher matcher = pattern.matcher("name=rob$name=bob");
Ilya Lysenko
  • 1,772
  • 15
  • 24

2 Answers2

2

With .matches(), you may use

Pattern pattern = Pattern.compile("\\p{Lower}+=\\p{Lower}+(?:\\$\\p{Lower}+=\\p{Lower}+)*"); // With `matches()` to ensure whole string match

Details

  • \p{Lower}+ - 1+ lowercase letters (use \p{L} to match any and \p{Alpha} to only match ASCII letters)
  • = - a = char
  • \p{Lower}+ - 1+ lowercase letters
  • (?:\\$\\p{Lower}+=\\p{Lower}+)* - 0 or more occurrences of:
    • \$ - a $ char
    • \p{Lower}+=\p{Lower}+ - 1+ lowercase letters, = and 1+ lowercase letters.

See the Java demo:

List<String> strs = Arrays.asList("name=alice$name=peter$name=angelina", "name=alicename=peter$name=angelina");
Pattern pattern = Pattern.compile("\\p{Lower}+=\\p{Lower}+(?:\\$\\p{Lower}+=\\p{Lower}+)*");
for (String str : strs)
    System.out.println("\"" + str + "\" => " + pattern.matcher(str).matches());

Output:

"name=alice$name=peter$name=angelina" => true
"name=alicename=peter$name=angelina" => false
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

You have extra ] and need to escape $ to use it as a character though you also need to match the last parameter without $ so use

([a-z]*=[a-z0-9]*(\$|$))*

[a-z]*= : match a-z zero or more times, match = character

[a-z0-9]*(\$|$): match a-z and 0-9, zero or more times, followed by either $ character or end of match.

([a-z]*=[a-z0-9]*(\$|$))*: match zero or more occurences of pairs.

Note: use + (one or more matches) instead of * for strict matching as:

([a-z]+=[a-z0-9]+(\$|$))*
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68