I have to check if the string provided has a specific format. The format is as follows: "This is just an #<example string>
just for test. This string has to be of this #<specific format>
".
If you look at the string, it has special characters #<>
with some string in between #<
and >
. I tried with regular expression: Pattern.compile("^[#<a-zA-Z0-9>]*$").matcher(string).find()
but it returns true even if I don't provide the special characters at the beginning or at the end.
I tried with an if condition too: if(string.matcher("#<"))
but I think this approach is lame. I'd rather go with the regular expresson.
What am I doing wrong here?
To match 1 or more "words" using the chars a-zA-Z0-9
between #<...>
and a whitespace boundary on the left and right, you could use
(?<!\S)#<[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*>(?!\S)
In Java
String regex = "(?<!\\S)#<[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*>(?!\\S)";
Try: Pattern.compile("#<(.*?)>")
Suggest you use a website like https://regex101.com/ to help you build these.
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.