java - 如果字符串在 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()。两者有什么区别,如果字符串以 结尾,删除字符串的最佳方法是什么?
解决方案
text.matches(".*OR$")
当匹配遍历整个字符串时。或者:
if (text.endsWith("OR"))
或者:
text = text.replaceFirst(" OR$", "");
推荐阅读
- java - 如何在通知中的操作上设置ClickListener
- json - 试图从世界时间 api 颤振发出 json 请求
- ruby - 如何在另一个 json 对象中总结/恢复 json 对象
- algorithm - 查找互斥数据以满足多个标准
- json - 如何访问 JSON API 中的整数值?
- javascript - 我如何覆盖这个伪边框 Html Css
- python - 有什么方法可以直接在 PySide2 中将自定义 Signal(int) 与 Push-Button 连接起来?
- python - 烧瓶,url_for()没有链接静态文件
- jquery - jQuery Ajax 调用刷新页面
- python - 我正在尝试使用 .get() 从复选框中获取一个值,但该值似乎没有改变