[英]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. 我想在Java中使用正则表达式匹配以“ test”开头或结尾的字符串。
Match Start of the string:- String a = "testsample"; 字符串的匹配开始:-字符串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"; 匹配字符串的结尾:-字符串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, 在matches
方法中,
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()
: 这是构建可与Matcher#find()
和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 见IDEONE演示
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
). 该pattern
看起来像^(\\Qtest\\E.*$|.*\\Qtest\\E)$
(请参见demo ),因为word
是作为一系列文字字符搜索的(这是通过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). matches
不需要的^
和$
是find
所必需的(它们也不阻止matches
匹配,因此也不会造成任何伤害)。
Also, note the (?s)
DOTALL inline modifier that makes a .
另外,请注意(?s)
DOTALL内联修饰符,使之成为.
match any character including a newline. 匹配任何字符, 包括换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.