Home Java javaTutorial Regular expression matching, replacement, search, and cutting methods in JAVA

Regular expression matching, replacement, search, and cutting methods in JAVA

Jan 22, 2017 pm 01:53 PM

正则表达式的查找;主要是用到String类中的split();

String str;

str.split();方法中传入按照什么规则截取,返回一个String数组

常见的截取规则:

str.split("\\.")按照.来截取

str.split(" ")按照空格截取

str.split("cc+")按照c字符来截取,2个c或以上

str.split((1)\\.+)按照字符串中含有2个字符或以上的地方截取(1)表示分组为1

截取的例子;

按照分组截取;截取的位置在两个或两个以上的地方

String str = "publicstaticccvoidddmain";
   //对表达式进分组重用
   String ragex1="(.)\\1+";
   String[] ss = str.split(ragex1);
   for(String st:ss){
   System.out.println(st);
   }
//按照两个cc+来截取
String ragex = " ";
  //切割
   String strs = "publicstaticccvoidddmain";
  String ragexs = "cc+";
  String[] s = strs.split(ragexs);
  for(String SSSS :s){
  System.out.println(SSSS);
  }
  System.out.println("=-=========");
Copy after login

正则表达式中的替换;

语法定义规则;

String s =str.replaceAll(ragex, newstr);
Copy after login

字符串中的替换是replace();

将4个或4个以上的连续的数字替换成*

// 替换
   String str="wei232123jin234";
   String ragex = "\\d{4,}";
   String newstr = "*";
   String s =str.replaceAll(ragex, newstr);
   System.out.println(s);
Copy after login

将重复的字符串换成一个*

String str ="wwweiei222222jjjiiinnn1232";
   String ragex ="(.)\\1+";
   String newStr ="*";
   String s = str.replaceAll(ragex, newStr);
   System.out.println(s);
Copy after login

将 我...我...要..要.吃...吃...饭 换成 我要吃饭

String str = "我...我...要..要.吃...吃...饭";
  String regex = "\\.+";
  String newStr = "";
  str=test(str, regex, newStr);
  regex = "(.)\\1+";
  newStr = "$1";
  test(str, regex, newStr);
public static String test(String str, String regex, String newStr) {
  String str2 = str.replaceAll(regex, newStr);
  System.out.println(str2);
  return str2;
 }
Copy after login

正则表达式的字符串的获取

1,根据定义的正则表达式创建Pattern对象

2,使用Pattern对象类匹配

3,判断是否为true

4,加入到组

例子;

String str = "public static void main(String[] args)"
    + " public static void main(String[] args)public static void main(String[] args)";
 String ragex = "\\b[a-zA-Z]{4,5}\\b";
 Pattern p =Pattern.compile(ragex);
 Matcher m = p.matcher(str);
    while(m.find()){
    String s = m.group();
    System.out.println(s);
    }
Copy after login

作业:

1,获取user中的user

String str ="<html>user</html>";
String regex = "<html>|</html>";
 String newStr = "";
String str2 = str.replaceAll(regex, newStr);
System.out.println(str2);
Copy after login

2,获取dhfjksaduirfn 11@qq.com dsjhkfa wang@163.com wokaz中的邮箱号码

String regex = " ";
String[] strs=str.split(regex);
 for(String str2:strs){
 String ragexDemo = "[a-zA-Z0-9]([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*"
 + "@([a-zA-Z0-9]+)\\.[a-zA-Z]+\\.?[a-zA-Z]{0,2}";
Pattern p = Pattern.compile(ragexDemo);
Matcher m = p.matcher(str2);
while(m.find()){
System.out.println(m.group());
  }
 }
Copy after login

示例代码:

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class test {
  public static void main(String[] args) {
    getStrings(); //用正则表达式获取指定字符串内容中的指定内容
    System.out.println("********************");
    replace(); //用正则表达式替换字符串内容
    System.out.println("********************");
    strSplit(); //使用正则表达式切割字符串
    System.out.println("********************");
    strMatch(); //字符串匹配
  }
 
  private static void strMatch() {
    String phone = "13539770000";
    //检查phone是否是合格的手机号(标准:1开头,第二位为3,5,8,后9位为任意数字)
    System.out.println(phone + ":" + phone.matches("1[358][0-9]{9,9}")); //true 
     
    String str = "abcd12345efghijklmn";
    //检查str中间是否包含12345
    System.out.println(str + ":" + str.matches("\\w+12345\\w+")); //true
    System.out.println(str + ":" + str.matches("\\w+123456\\w+")); //false
  }
 
  private static void strSplit() {
    String str = "asfasf.sdfsaf.sdfsdfas.asdfasfdasfd.wrqwrwqer.asfsafasf.safgfdgdsg";
    String[] strs = str.split("\\.");
    for (String s : strs){
      System.out.println(s);
    }   
  }
 
  private static void getStrings() {
    String str = "rrwerqq84461376qqasfdasdfrrwerqq84461377qqasfdasdaa654645aafrrwerqq84461378qqasfdaa654646aaasdfrrwerqq84461379qqasfdasdfrrwerqq84461376qqasfdasdf";
    Pattern p = Pattern.compile("qq(.*?)qq");
    Matcher m = p.matcher(str);
    ArrayList<String> strs = new ArrayList<String>();
    while (m.find()) {
      strs.add(m.group(1));     
    }
    for (String s : strs){
      System.out.println(s);
    }   
  }
 
  private static void replace() {
    String str = "asfas5fsaf5s4fs6af.sdaf.asf.wqre.qwr.fdsf.asf.asf.asf";
    //将字符串中的.替换成_,因为.是特殊字符,所以要用\.表达,又因为\是特殊字符,所以要用\\.来表达.
    str = str.replaceAll("\\.", "_");
    System.out.println(str);   
  }
}
Copy after login

   更多JAVA中正则表达式匹配,替换,查找,切割的方法相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

See all articles