首页 > 解决方案 > 如果字符串在 java 中结束,则删除它

问题描述

如果它以给定的字符串结尾,我必须删除“OR”。

public class StringReplaceTest {

    public static void main(String[] args) {
        String text = "SELECT count OR %' OR";
        System.out.println("matches:" + text.matches("OR$"));

        Pattern pattern = Pattern.compile("OR$");
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println("Found match at: " + matcher.start() + " to " + matcher.end());
            System.out.println("substring:" + text.substring(matcher.start(), matcher.end()));
            text = text.replace(text.substring(matcher.start(), matcher.end()), "");
            System.out.println("after replace:" + text);
        }

    }
}

输出:

matches:false
Found match at: 19 to 21
substring:OR
after replace:SELECT count  %' 

它删除了所有出现的字符串“OR”,但如果它仅以结尾,我必须删除。怎么做 ?

正则表达式也适用于 Pattern,但不适用于 String.matches()。两者有什么区别,如果字符串以 结尾,删除字符串的最佳方法是什么?

标签: javaregex

解决方案


text.matches(".*OR$")当匹配遍历整个字符串时。或者:

if (text.endsWith("OR"))

或者:

text = text.replaceFirst(" OR$", "");

推荐阅读