繁体   English   中英

如何在Java中使用正则表达式匹配给定字符串的开头或结尾

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

我想在Java中使用正则表达式匹配以“ test”开头或结尾的字符串。

字符串的匹配开始:-字符串a =“ testsample”;

  String pattern = "^test";

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

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

匹配字符串的结尾:-字符串a =“ sampletest”;

  String pattern = "test$";

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

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

如何将正则表达式与给定字符串的开头或结尾进行组合?

只需使用正则表达式交替运算符|

String pattern = "^test|test$";

matches方法中,

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

使用此代码

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

这是构建可与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)); 

IDEONE演示

pattern看起来像^(\\Qtest\\E.*$|.*\\Qtest\\E)$ (请参见demo ),因为word是作为一系列文字字符搜索的(这是通过Pattern.quote实现的)。 matches不需要的^$find所必需的(它们也不阻止matches匹配,因此也不会造成任何伤害)。

另外,请注意(?s) DOTALL内联修饰符,使之成为. 匹配任何字符, 包括换行符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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