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");
1
  • 1
    Just split string by $ and check Commented Apr 13, 2020 at 16:29

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

And when I have also "name=alice&name=" or "=alice&name=bob", how to add empty string in regex?
@AliceVictoria Then use * quantifiers, ideone.com/p5mgo2
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]+(\$|$))*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.