Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match start or end of given string using regex in java

Tags:

java

regex

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 ?

like image 355
Galet Avatar asked Jan 22 '16 05:01

Galet


3 Answers

Just use regex alternation operator |.

String pattern = "^test|test$";

In matches method, it would be,

string.matches("test.*|.*test");
like image 91
Avinash Raj Avatar answered Oct 10 '22 11:10

Avinash Raj


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);
like image 41
Ajmal Muhammad Avatar answered Oct 10 '22 11:10

Ajmal Muhammad


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.

like image 36
Wiktor Stribiżew Avatar answered Oct 10 '22 11:10

Wiktor Stribiżew