java中,正则表达式的使用 (最普通使用,Group,贪婪模式)

2024-03-04 08:32

本文主要是介绍java中,正则表达式的使用 (最普通使用,Group,贪婪模式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

0.最普通的使用

1.正则表达式有Group功能。

2.正则表达式中的贪婪模式, 非贪婪模式(*?)

3.find() 与 matches() 之间的区别

↓循环获取所有文件

↓文件内部内容读取操作

Files.lines 这个方法是java8中,新增加的方法。

Stream 构造类时,指定泛型,传递到方法中使用。

■扩展

1.正则表达式中^的用法

用法一:   限定开头

用法二:(否)取反

区别方法

■ Summary of regular-expression constructs


java中,正则表达式的使用

0.最普通的使用

Pattern ptn;
Matcher matStr;
String checkRE = ”^([a-zA-Z0-9])+([a-zA-Z0-9\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-])+$”ptn = Pattern.compile(checkRE);
matStr = ptn.matcher(str)if (!matStr.find()){return false;
}

2020 / 01 / 05

以上所写的只是最基本的使用。除此之外还有以下功能

1.正则表达式有Group功能。

import java.util.regex.Matcher;
import java.util.regex.Pattern;class HelloWorld {public static void main(String args[]){String checkRE = "^([a-zA-Z0-9])+@([a-zA-Z0-9\\.]+)$";Pattern ptn = Pattern.compile(checkRE);Matcher matStr = ptn.matcher("sxz@csnd.com");System.out.println(matStr.find());System.out.println(matStr.groupCount());System.out.println(matStr.group(2));}
}

--

运行结果如下

true
2
csnd.com

--

使用group定义正则之后,我们不但可以使用原有的匹配功能,

还可以指定我们想要抽出部分的内容

2.正则表达式中的贪婪模式, 非贪婪模式(*?)

import java.util.regex.Matcher;
import java.util.regex.Pattern;class HelloWorld {public static void main(String args[]){String checkRE = "^([a-zA-Z0-9])+@([a-zA-Z0-9\\.]+)$";Pattern ptn = Pattern.compile(checkRE);Matcher matStr = ptn.matcher("sxz@csnd.com");System.out.println(matStr.find());System.out.println(matStr.groupCount());System.out.println(matStr.group(2));System.out.println(matStr.group());System.out.println("--------------------------");// 正则表达式中的贪婪模式 默认开启checkRE = "<div>.*</div>";ptn = Pattern.compile(checkRE);matStr = ptn.matcher("sxzaadivaa<div>123</div><div>456</div>aaass");System.out.println(matStr.find());System.out.println(matStr.groupCount());System.out.println(matStr.group()+"   位置:["+matStr.start()+","+matStr.end()+"]");System.out.println("--------------------------");// 正则表达式中 非贪婪模式 (使用「?」)checkRE = "<div>.*?</div>*";ptn = Pattern.compile(checkRE);matStr = ptn.matcher("sxzaadivaa<div>123</div><div>456</div>aaass");System.out.println(matStr.find());System.out.println(matStr.groupCount());System.out.println(matStr.group()+"   位置:["+matStr.start()+","+matStr.end()+"]");System.out.println("--------------------------");}
}

以上代码,运行结果如下。

------------------------------------

3.find() 与 matches() 之间的区别

find()

package com.sxz.test;import java.util.regex.Matcher;
import java.util.regex.Pattern;public class TestPatternFindMatches {public static void main(String[] args) {int count = 0;String regEx = "[\\u4e00-\\u9fa5]";String str = "中文fdas ";Pattern p = Pattern.compile(regEx);Matcher m = p.matcher(str);while (m.find()) {count = count + 1;System.out.println(m.groupCount());System.out.println(m.group());}System.out.println("共有 " + count + "个 ");}
}

 ---

matches()   //下面 代码 33行中使用

整理中。。。

package com.sxz.test;import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;public class TestFileOperate {private static String BATH_PATH = "C:\\test\\";private static String COLUMN_REGEX="<itemName>.*?</itemName>";public static int count;public static void main(String[] args) {getFileNameAndPrintColumnName("test001");}public static void getFileNameAndPrintColumnName(String folderName){File[] files = listFilesMatching(BATH_PATH + folderName, ".*\\.(txt|TXT)$");List<File> listFile = Arrays.asList(files);listFile.stream().forEach(readFileTxt -> process(readFileTxt));}private static File[] listFilesMatching(String path, String regex){final Pattern p = Pattern.compile(regex);return new File(path).listFiles(file -> p.matcher(file.getName()).matches());}private static void process(File readFileTxt){System.out.println("---" + readFileTxt.getName() + "------START");count = 0;final Pattern ptn = Pattern.compile(COLUMN_REGEX);try(Stream<String> lines = Files.lines(readFileTxt.toPath(),Charset.forName("UTF-8"))){lines.forEach(line->{Matcher match = ptn.matcher(line);if(match.find()){System.out.println(match.group());count = count + 1;}});} catch (IOException e) {e.printStackTrace();}System.out.println("---" + readFileTxt.getName() + " 项目数:" + count + "------END");}}

---

↓循环获取所有文件

----

----

---

 ---

↓文件内部内容读取操作

============================================

 ---

Files这类,是1.7中,新增加的类。

---

Files.lines 这个方法是java8中,新增加的方法。

读取一个文件中所有的行。 

 ---

  ---

Stream中的forEach方法

 ----

Stream<T> 构造类时,指定泛型,传递到方法中使用。

---

■扩展

1.正则表达式中^的用法

用法一:   限定开头

文档上给出了解释是匹配输入的开始,如果多行标示被设置成了true,同时会匹配后面紧跟的字符

比如 /^A/会匹配"An e"中的A,但是不会匹配"ab A"中的A/[(^\s+)(\s+$)]/g(^cat)$(^cat$)^(cat)$^(cat$)

用法二:(否)取反

当这个字符出现在一个字符集合模式的第一个字符时,他将会有不同的含义。

比如: /[^a-z\s]/会匹配"my 3 sisters"中的"3"  
这里的”^”的意思是字符类的否定,
上面的正则表达式的意思是匹配不是(a到z和空白字符)的字符。 [^a]表示“匹配除了a的任意字符”。[^a-zA-Z0-9]表示“找到一个非字母也非数字的字符”。[\^abc]表示“找到一个插入符或者a或者b或者c”。

区别方法

经过对比,只要是”^”这个字符是在中括号”[]”中被使用的话就是表示字符类的否定,

如果不是的话就是表示限定开头。我这里说的是直接在”[]”中使用,不包括嵌套使用。 

其实也就是说”[]”代表的是一个字符集,”^”只有在字符集中才是反向字符集的意思。

----

■ Summary of regular-expression constructs

■Character classes 
[abc] a, b, or c (simple class) 
[^abc] Any character except a, b, or c (negation) 
[a-zA-Z] a through z or A through Z, inclusive (range) 
[a-d[m-p]] a through d, or m through p: [a-dm-p] (union) 
[a-z&&[def]] d, e, or f (intersection) 
[a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction) 
[a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction) ■Predefined character classes 
. Any character (may or may not match line terminators) 
\d A digit: [0-9] 
\D A non-digit: [^0-9] 
\h A horizontal whitespace character: [ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000] 
\H A non-horizontal whitespace character: [^\h] 
\s A whitespace character: [ \t\n\x0B\f\r] 
\S A non-whitespace character: [^\s] 
\v A vertical whitespace character: [\n\x0B\f\r\x85\u2028\u2029]  
\V A non-vertical whitespace character: [^\v] 
\w A word character: [a-zA-Z_0-9] 
\W A non-word character: [^\w] ■Boundary matchers 
^ The beginning of a line 
$ The end of a line 
\b A word boundary 
\B A non-word boundary 
\A The beginning of the input 
\G The end of the previous match 
\Z The end of the input but for the final terminator, if any 
\z The end of the input ■Characters 
x The character x 
\\ The backslash character 
\0n The character with octal value 0n (0 <= n <= 7) 
\0nn The character with octal value 0nn (0 <= n <= 7) 
\0mnn The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7) 
\xhh The character with hexadecimal value 0xhh 
\uhhhh The character with hexadecimal value 0xhhhh 
\x{h...h} The character with hexadecimal value 0xh...h (Character.MIN_CODE_POINT  <= 0xh...h <=  Character.MAX_CODE_POINT) 
\t The tab character ('\u0009') 
\n The newline (line feed) character ('\u000A') 
\r The carriage-return character ('\u000D') 
\f The form-feed character ('\u000C') 
\a The alert (bell) character ('\u0007') 
\e The escape character ('\u001B') 
\cx The control character corresponding to x ■POSIX character classes (US-ASCII only) 
\p{Lower} A lower-case alphabetic character: [a-z] 
\p{Upper} An upper-case alphabetic character:[A-Z] 
\p{ASCII} All ASCII:[\x00-\x7F] 
\p{Alpha} An alphabetic character:[\p{Lower}\p{Upper}] 
\p{Digit} A decimal digit: [0-9] 
\p{Alnum} An alphanumeric character:[\p{Alpha}\p{Digit}] 
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 
\p{Graph} A visible character: [\p{Alnum}\p{Punct}] 
\p{Print} A printable character: [\p{Graph}\x20] 
\p{Blank} A space or a tab: [ \t] 
\p{Cntrl} A control character: [\x00-\x1F\x7F] 
\p{XDigit} A hexadecimal digit: [0-9a-fA-F] 
\p{Space} A whitespace character: [ \t\n\x0B\f\r] ■java.lang.Character classes (simple java character type) 
\p{javaLowerCase} Equivalent to java.lang.Character.isLowerCase() 
\p{javaUpperCase} Equivalent to java.lang.Character.isUpperCase() 
\p{javaWhitespace} Equivalent to java.lang.Character.isWhitespace() 
\p{javaMirrored} Equivalent to java.lang.Character.isMirrored() ■Classes for Unicode scripts, blocks, categories and binary properties 
\p{IsLatin} A Latin script character (script) 
\p{InGreek} A character in the Greek block (block) 
\p{Lu} An uppercase letter (category) 
\p{IsAlphabetic} An alphabetic character (binary property) 
\p{Sc} A currency symbol 
\P{InGreek} Any character except one in the Greek block (negation) 
[\p{L}&&[^\p{Lu}]] Any letter except an uppercase letter (subtraction) ■Linebreak matcher 
\R Any Unicode linebreak sequence, is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]  ■Greedy quantifiers 
X? X, once or not at all 
X* X, zero or more times 
X+ X, one or more times 
X{n} X, exactly n times 
X{n,} X, at least n times 
X{n,m} X, at least n but not more than m times ■Reluctant quantifiers 
X?? X, once or not at all 
X*? X, zero or more times 
X+? X, one or more times 
X{n}? X, exactly n times 
X{n,}? X, at least n times 
X{n,m}? X, at least n but not more than m times ■Possessive quantifiers 
X?+ X, once or not at all 
X*+ X, zero or more times 
X++ X, one or more times 
X{n}+ X, exactly n times 
X{n,}+ X, at least n times 
X{n,m}+ X, at least n but not more than m times ■Logical operators 
XY X followed by Y 
X|Y Either X or Y 
(X) X, as a capturing group ■Back references 
\n Whatever the nth capturing group matched 
\k<name> Whatever the named-capturing group "name" matched ■Quotation 
\ Nothing, but quotes the following character 
\Q Nothing, but quotes all characters until \E 
\E Nothing, but ends quoting started by \Q ■Special constructs (named-capturing and non-capturing) 
(?<name>X) X, as a named-capturing group 
(?:X) X, as a non-capturing group 
(?idmsuxU-idmsuxU)  Nothing, but turns match flags i d m s u x U on - off 
(?idmsux-idmsux:X)   X, as a non-capturing group with the given flags i d m s u x on - off 
(?=X) X, via zero-width positive lookahead 
(?!X) X, via zero-width negative lookahead 
(?<=X) X, via zero-width positive lookbehind 
(?<!X) X, via zero-width negative lookbehind 
(?>X) X, as an independent, non-capturing group 

----

这篇关于java中,正则表达式的使用 (最普通使用,Group,贪婪模式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/772613

相关文章

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

idea maven编译报错Java heap space的解决方法

《ideamaven编译报错Javaheapspace的解决方法》这篇文章主要为大家详细介绍了ideamaven编译报错Javaheapspace的相关解决方法,文中的示例代码讲解详细,感兴趣的... 目录1.增加 Maven 编译的堆内存2. 增加 IntelliJ IDEA 的堆内存3. 优化 Mave

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码

SpringBoot利用@Validated注解优雅实现参数校验

《SpringBoot利用@Validated注解优雅实现参数校验》在开发Web应用时,用户输入的合法性校验是保障系统稳定性的基础,​SpringBoot的@Validated注解提供了一种更优雅的解... 目录​一、为什么需要参数校验二、Validated 的核心用法​1. 基础校验2. php分组校验3

Pydantic中Optional 和Union类型的使用

《Pydantic中Optional和Union类型的使用》本文主要介绍了Pydantic中Optional和Union类型的使用,这两者在处理可选字段和多类型字段时尤为重要,文中通过示例代码介绍的... 目录简介Optional 类型Union 类型Optional 和 Union 的组合总结简介Pyd

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti