簡體   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