Interpretation of regular expression in java

什么是正则表达式

一个特殊字符串,用于描述匹配一个字符串集合的模式。可以用它来进行字符串的匹配、替换和拆分。

正则表达式语法

用于匹配符合某一特征的字符串

MetacharacterDescription
|Find a match for any one of the patterns separated by | as in: cat|dog|fish
.Find just one instance of any character
^Finds a match as the beginning of a string as in: ^Hello
$Finds a match at the end of the string as in: World$
\dFind a digit
\sFind a whitespace character
\bFind a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
\uxxxxFind the Unicode character specified by the hexadecimal number xxxx

用于搜索在某一范围内的字符

ExpressionDescription
[abc]Find one character from the options between the brackets
[^abc]Find one character NOT between the brackets
[0-9]Find one character from the range 0 to 9

用于匹配字符出现的次数

QuantifierDescription
n+Matches any string that contains at least one n
n*Matches any string that contains zero or more occurrences of n
n?Matches any string that contains zero or one occurrences of n
n{x}Matches any string that contains a sequence of X n's
n{x,y}Matches any string that contains a sequence of X to Y n's
n{x,}Matches any string that contains a sequence of at least X n's

匹配字符串

使用String中的matches方法来匹配字符串,返回True或者False

替换和拆分字符串

使用String中的replaceAll方法替换所有匹配的子字符串,类似的方法还有replaceFirst

使用split方法将一个字符串以匹配的分隔符拆分为子字符串

note

正则表达式以元表达式的形式给出,Java中若要使用 \ 要以转义字符 \\ 表示

默认情况下,量词符都是贪婪的,如

System.out.println(“Jaaavaa".replaceFirst("a+","R"));

会匹配到 aaa ,可以通过在正则表达式后面加?使量词符变为惰性,如

System.out.println(“Jaaavaa".replaceFirst("a+?","R"));

会匹配到 a 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值