简体   繁体   中英

regex match hyphen slash alphanumeric in parentheses

I have a String to match with regex

String str = "(1a/2s-/-)"

The conditions I need to get:

  1. There has to be a parentheses
  2. only alphanumeric dash and slash could be inside parentheses and it repeats

regex I have tried so far

([A-Za-z0-9] / [A-Za-z0-9]+)

Does anyone could help me solve this?

What you're missing is you need to escape the special characters that have meaning to a regular expression. Such as parenthesis, dashes and slashes.

\\([a-zA-Z0-9\\-\\/]+\\)

If you need to force that the string is nothing but this then make it looks like this:

^\\([a-zA-Z0-9\\-\\/]+\\)$

The ^ and the $ mean it must start and end with this respectively.


Broken down:

^ = Must start with
\\( = An opening parenthesis
[a-zA-Z0-9\\-\\/]+ = At least one or more alphanumeric chars, dashes or forward slashes
\\) = A closing parenthesis
$ = Must end with

You can use this regex:

^\([A-Za-z0-9\-\/]+\)$

You need to escape parentheses and put slash and dash into your character set. ^ and $ is optional if you want to match the string from the beginning to end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM