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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With