0

The following piece of code checks for same variable portion /en(^$|.*) which is empty or any characters. So the expression should match /en AND /en/bla, /en/blue etc. But the expression doesn't work when checking for just /en.

"/en".matches("/en(^$|.*)")

Is there a way to make this empty regex check (^$) perform with java?

edit

I mean: Is there a way to make this piece of code return true?

2 Answers 2

4

What you're currently doing is checking whether en is followed by the start of string then the end of string (which doesn't make sense, since the start of string needs to be first) or anything else. This should work:

"/en".matches("/en(|.*)")

Or just using ? (optional):

"/en".matches("/en(.*)?")

But it's rather pointless, since * is zero or more (so a blank string will match for .*), just this should do it:

"/en".matches("/en.*")

EDIT:

Your code was already returning true, but it was not matching the ^$ part, but rather .* (similar to the above).

I should point out that you may as well use startsWith, unless your real data is more complex:

"/en".startsWith("/en")
Sign up to request clarification or add additional context in comments.

9 Comments

(|.*) == (.*)? == (.*)
@DuncanJones If you use matches capturing groups have no purpose that I know of. And I'm sure OP can add it back if he/she needs it.
Using your thought the final regex would become something like this. (|\\/.*$). thanks for the help!
@justastefan "/en".matches("/en(|.*)") is completely equivalent to "/en".matches("/en.*").
@justastefan How about "/en(/.*)?"?
|
3

Is there a way to make this piece of code return true?

"/en".matches("/en(^$|.*)")

That code does return true. Just try it!

However, your pattern is unnecessarily complex. Try:

"/en".matches("/en.*")

This will match /en followed by anything (including nothing).

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.