怎么在Java中对String类进行正则操作

发布时间:2021-04-09 16:14:07 作者:Leah
来源:亿速云 阅读:170

怎么在Java中对String类进行正则操作?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

一 应用正则表达式

1 代码

public class RegExp
{
  public static void main(String[] args) throws Exception
  {
    if ("123".matches("\\d+"))
    {
      System.out.println("由数字组成!");
    } else
    {
      System.out.println("不是由数字组成!");
    }
  }
}

2 运行

由数字组成!

二 字符串替换——过滤字符串中的数字

1 代码

public class SubString
{
  public static void main(String[] args) throws Exception
  {
    String str = "a1b22c333d4444e55555f6666666g";
    String regex = "[0-9]+"; // 数字出现1次或多次
    //String regex = "\\d+"; // 数字出现1次或多次
    System.out.println(str.replaceAll(regex, ""));
  }
}

2 运行

abcdefg

三 正则验证邮箱格式

1 代码

import java.util.*;
public class EmailValidation
{
  public static void main(String[] args) throws Exception
  {
    String str = null;
    String regex = "\\w+@\\w+.\\w+";
    Scanner reader = new Scanner(System.in);
    do
    {
      System.out.print("请输入一个有效的邮件地址:");
      str = reader.next();
      System.out.println(str);
    } while (!str.matches(regex));
    System.out.println("邮件地址有效!谢谢注册!");
    reader.close();
  }
}

2 运行

请输入一个有效的邮件地址:4月好
4月好
请输入一个有效的邮件地址:yy@qq.com
yy@qq.com
邮件地址有效!谢谢注册!

看完上述内容,你们掌握怎么在Java中对String类进行正则操作的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 怎么在Python中对元组进行操作
  2. 怎么在Java中对字符数组、String类、StringBuffer三者进行转换

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

java string类

上一篇:如何在Java中使用日期操作类

下一篇:使用java怎么统计字符串中的大写字母

相关阅读

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

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