Java正则表达式如何匹配特定字符串结尾

发布时间:2025-04-10 09:14:45 作者:小樊
来源:亿速云 阅读:107

在Java中,要使用正则表达式匹配特定字符串结尾,你可以使用$符号。$符号表示字符串的结尾。下面是一个简单的例子,演示如何使用正则表达式匹配以"hello"结尾的字符串:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String input = "This is a test string hello";
        String regex = ".*hello$";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            System.out.println("匹配成功,字符串以 'hello' 结尾");
        } else {
            System.out.println("匹配失败,字符串不是以 'hello' 结尾");
        }
    }
}

在这个例子中,我们使用了正则表达式".*hello$".表示任意字符,*表示匹配0个或多个字符,hello表示我们要匹配的特定字符串,$表示字符串的结尾。因此,这个正则表达式会匹配任何以"hello"结尾的字符串。

推荐阅读:
  1. 一个基于SpringCloud设计精良的网上商城的实现方法
  2. 什么是线程死锁

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:怎样用Java正则表达式匹配HTML标签

下一篇:怎样用Java正则表达式匹配单词边界

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》