0

I am new to regex and am having trouble making this work. The following line returns false but I think it should return true.

Pattern.matches("^DOI", "DOI 10.1364/OL.36.002946")

What I want is to match the first three letters "DOI", regardless of what comes after it. I try to remove the anchor but it still does not match. Can anyone help explain it for me?

3 Answers 3

4

Just use

String yourVar = "DOI dskljdj";
if (yourVar.startsWith("DOI")) { ... }

It will check if your String begins with DOI or not.

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

Comments

2

You can try with

System.out.println(Pattern.matches("^DOI.*", "DOI 10.1364/OL.36.002946"));

You want your text to start with DOI and after that you just want any amount of any character .*

However as stated in the other responses, String.startWith is way better if you are only checking that your string starts with a fixed prefix. Regexp will allow you to do more powerful things though, however it is more painful performance wise (and way more complex code wise).

2 Comments

Consider that Pattern.matches is less efficient than .startsWith in this case. If you have only one check, use .startsWith.
Agree, if you only want to check that your string begins with a predefined string you don't need a regexp for that.
0

This is the best route to go

String.startsWith("DOI");

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.