java 如何在java中使用正则表达式匹配给定字符串的开始或结束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34939576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:34:35  来源:igfitidea点击:

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

javaregex

提问by Galet

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

匹配字符串的开头:- 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 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 ?

如何将开始或结束的正则表达式与给定的字符串结合使用?

回答by Avinash Raj

Just use regex alternation operator |.

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

String pattern = "^test|test$";

In matchesmethod, it would be,

matches方法上,它会是,

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

回答by Ajmal Muhammad

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

回答by Wiktor Stribi?ew

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 patternwill look like ^(\Qtest\E.*$|.*\Qtest\E)$(see demo) since the wordis searched for as a sequence of literal characters (this is achieved with Pattern.quote). The ^and $that are not necessary for matchesare necessary for find(and they do not prevent matchesfrom matching, either, thus, do not do any harm).

pattern会像^(\Qtest\E.*$|.*\Qtest\E)$(见演示),因为word中搜索作为文本字符的序列(这是与实现Pattern.quote)。在^$那些没有必要的matches是必要的find(他们不阻止matches从匹配,要么,因此不会做任何伤害)。

Also, note the (?s)DOTALL inline modifier that makes a .match any character includinga newline.

另外,请注意(?s)DOTALL 内联修饰符,它可以.匹配任何字符,包括换行符。