6

I want to match a string which starts or ends with a "test" using regex in java.

Match Start of the string:- String a = "testsample";

  String pattern = "^test";

  // Create a Pattern object
  Pattern r = Pattern.compile(pattern);

  // Now create matcher object.
  Matcher m = r.matcher(a);

Match End of the string:- String a = "sampletest";

  String pattern = "test$";

  // Create a Pattern object
  Pattern r = Pattern.compile(pattern);

  // Now create matcher object.
  Matcher m = r.matcher(a);

How can I combine regex for starts or ends with a given string ?

3 Answers 3

18

Just use regex alternation operator |.

String pattern = "^test|test$";

In matches method, it would be,

string.matches("test.*|.*test");
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to use "test" string at once in regex or inside matches method
3

use this code

String string = "test";
String pattern = "^" + string+"|"+string+"$";

// Create a Pattern object
Pattern r = Pattern.compile(pattern);

// Now create matcher object.
Matcher m = r.matcher(a);

2 Comments

This is the same solution as @AvinashRaj
I did, and you are proposing the same regex.
1

Here is how you can build a dynamic regex that you can use both with Matcher#find() and Matcher#matches():

String a = "testsample";
String word = "test";
String pattern = "(?s)^(" + Pattern.quote(word) + ".*$|.*" + Pattern.quote(word) + ")$";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(a);
if (m.find()){
    System.out.println("true - found with Matcher"); 
} 
// Now, the same pattern with String#matches:
System.out.println(a.matches(pattern)); 

See IDEONE demo

The pattern will look like ^(\Qtest\E.*$|.*\Qtest\E)$ (see demo) since the word is searched for as a sequence of literal characters (this is achieved with Pattern.quote). The ^ and $ that are not necessary for matches are necessary for find (and they do not prevent matches from matching, either, thus, do not do any harm).

Also, note the (?s) DOTALL inline modifier that makes a . match any character including a newline.

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.