1

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 a-z 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

4
  • (\/[^#\?]+) ? Commented Dec 8, 2016 at 21:23
  • 1
    when you ask a question about regex, add a tag for the language or the tool you use. Commented Dec 8, 2016 at 21:23
  • Sorry about that.... Alex the regex you gave me does not work on the string "/#test" where it should grab the / only Commented Dec 8, 2016 at 21:25
  • What if you have a longer path like /hello/there#test or if the string doesn't have a #? Commented Dec 8, 2016 at 21:30

2 Answers 2

2

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

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

Comments

2

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)

2 Comments

Note that capturing the whole pattern is redundant in Java since you always have access to the whole match via Matcher.group() (or Matcher.group(0)).
@WiktorStribiżew Ah, he used java tag, and I missed it. Thank you for notice.

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.