I have the regular expression
[/].([a-z/!@$%^&*()-+><~*\.]+)
which I am trying to capture everything after the / (inclusive) up to a # or ? (exclusive).
The strings I have tried the regex on:
/hello.there#test properly gives me the /hello.there
however trying it on just / does not group anything. It does not group anything in the string /h as well. I thought it would do it for that because I included az in the set to capture.
How can I improve the regex so that it captures / (inclusive) and everything after excluding # and ? while ignoring anything after # and ?
Thank you
When you need to match some chars other than some other characters, you should think of negated character classes .
To match any char but #
and ?
use [^#?]
. To match zero or more occurrences, add *
after it. Use
/([^#?]*)
See the regex demo
String str = "/hello.there#test";
Pattern ptrn = Pattern.compile("/([^#?]*)");
Matcher matcher = ptrn.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group()); // => /hello.there
System.out.println(matcher.group(1)); // => hello.there
}
If you want to ignore characters after just #
and ?
, then exclude those directly.
(/[^#?]*)
In this regex, /
is in the group so you can capture it, and [^#?]
includes all characters except #
and ?
.(of course, any characters after those will ignored)
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.