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

正则表达式的查找;主要是用到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("=-=========");

   

正则表达式中的替换;

语法定义规则;

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

   

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

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

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

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

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

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

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;
 }

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

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);
    }

   

作业:

1,获取user中的user

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

   

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());
  }
 }

   

示例代码:

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);   
  }
}

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

Statement
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
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 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...

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 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...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor