2

Lets assume I have a string:

asdf/dfa/fds?adsf

I want to be able to get the string: asdf?adsf

So essentially I want to parse out everything from the first '/' to the '?'.

I tried experimenting with it (see example below) but I couldn't get it to work:

s = s.replaceAll("\\/([?]*)", "");

3 Answers 3

2

You should change it to this:

s = s.replaceAll("/.*(?=\\?)", "");

(?=\\?) is a look-ahead that means "the next character is a literal ?". (FYI, unescaped, ? has special meaning in a regex.)


However, you did not mention what should happen if there are multiple ?. The regex above will match until the last one.

If you want to match until the first,

s = s.replaceAll("/.*?(?=\\?)", "");

The extra ? causes the repeated match to be "reluctant".

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need to escape / so no \\ is needed before /. Also it seems that OP input is link so there cant be any second ? in it, but I like the way you include this possibility in your answer :)
@Pshemo: "it seems". I guess so?
1

This should do the trick

replaceAll("/[^?]*", "")

/[^?]* will match first / and all non-? characters after it.

Comments

1

try this

String s = "asdf/dfa/fds?adsf".replaceAll("/.*(?=\\?)", "");

Comments

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.