简体   繁体   中英

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

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 ?

Just use regex alternation operator | .

String pattern = "^test|test$";

In matches method, it would be,

string.matches("test.*|.*test");

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM