[英]How to match a string's end using a regex pattern in Java?
I want a regular expression pattern that will match with the end of a string.我想要一个与字符串末尾匹配的正则表达式模式。
I'm implementing a stemming algorithm that will remove suffixes of a word.我正在实现一个词干算法,将删除一个词的后缀。
Eg for a word 'Developers' it should match 's'.例如,对于单词“Developers”,它应该匹配“s”。
I can do it using following code :我可以使用以下代码来做到这一点:
Pattern p = Pattern.compile("s");
Matcher m = p.matcher("Developers");
m.replaceAll(" "); // it will replace all 's' with ' '
I want a regular expression that will match only a string's end something like replaceLast()
.我想要一个仅匹配字符串结尾的正则表达式,例如replaceLast()
。
You need to match "s", but only if it is the last character in a word.您需要匹配“s”,但前提是它是单词中的最后一个字符。 This is achieved with the boundary assertion $:这是通过边界断言 $ 实现的:
input.replaceAll("s$", " ");
If you enhance the regular expression, you can replace multiple suffixes with one call to replaceAll:如果增强正则表达式,则可以通过一次调用 replaceAll 替换多个后缀:
input.replaceAll("(ed|s)$", " ");
使用$
:
Pattern p = Pattern.compile("s$");
public static void main(String[] args)
{
String message = "hi this message is a test message";
message = message.replaceAll("message$", "email");
System.out.println(message);
}
Check this, http://docs.oracle.com/javase/tutorial/essential/regex/bounds.html检查这个, http://docs.oracle.com/javase/tutorial/essential/regex/bounds.html
看看下面的例子:
String ss = "Developers".replaceAll(".$", " ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.