chrisrhyno2003
chrisrhyno2003

Reputation: 4177

Match a String with optional number of hyphens - Java Regex

I am trying to match Strings with optional number of hyphens. For example, string1-string2, string1-string2-string3, string1-string2-string3 and so on.

Right now, I have something which matches one hyphen. How can I make the regex to match optional number of hyphens?

My current regex is: arn:aws:iam::\d{12}:[a-zA-Z]/?[a-zA-Z]-?[a-zA-Z]*

What do I need to add?

Upvotes: 0

Views: 1437

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

Use this regex:

^\\w+(-\\w+)*$

Explanation:

\\w+     - match any string containing [a-zA-Z_0-9]
(-\\w+)* - match a hyphen followed by a string zero or more times

Regex101

Note that this won't match an empty string, or a string containing weird characters. You could handle these cases manually or you could update the regex.

Upvotes: 2

Related Questions