Groovy系列之旅四(正则表达式基础)

正则表达式是字符串处理利器.简单的正则就是一些字符或数字.
包含一个最简单正则表达式的表达式是用==~.
比如说:
" beijing "   ==~   / beijing /
运行一下结果是true.
在这里有两件需要注意的事情,第一是
==~它和==操作符很像,但正则匹配模式已经代替了精确比较.
第二个是/,把表达式包含在/ 里面就是告诉groovy,把它当成正则
处理,而不是字符串.

我们可以在beijing后面加上?,表达字符g是可选的.

" beijing "   ==~   / beijing /
" beijin "   ==~/ beijing ?/
结果都为true.

现在我们定义一个方法,来检验指定字符串是否符合我们给定的
正则:
def check(a,b)
{
    
if(a ==~ b)
    
{
        println(
"spell ok")
    }

    
else
    
{
        println(
"error,try again")
    }

}
鉴于刚才上面提到的基础知识,我们输入如下内容进行测试:
regular  =   / zdw /
check(
" zdw "  , regular)
check(
" test " , regular)
theRegularExpression 
=   / Wisniew ? ski /
check(
" Wisniewski " , theRegularExpression)
check(
" Wisnieski " , theRegularExpression)
check(
" Wisniewewski " , theRegularExpression)

输出结果是:
spell ok
error,
try  again
spell ok
spell ok
error,
try  again

假定有字符串"lovebeijing" ,如果我们想让"beijing"变成可选的,比如换成"nanjing",这时
可以用(beijing | nanjing),注意|两边不能有空格:
regular  =   / love(beijing | nanjing) /     
check(
" lovebeijing " ,regular)
check(
" lovenanjing " ,regular)

上面两个表达式都是符合要求的.

(a | b) 只能出现其中和一个,且一次.

我们再来看看其它一些例子:
theRegularExpression  =   / Wis[abcd]niewski /   //  'a', 'b', 'c', 'd' 其中的一个
theRegularExpression  =   / Wis[abcd] ? niewski /   //  'a', 'b', 'c', 'd' 其中的一个,但不是必须的
theRegularExpression  =   / Wis[a - zA - Z]niewski /   //  必须有一个从a-z的大写或小写字符出现
theRegularExpression  =   / Wis[ ^ abcd]niewski /   //  除'a','b','c','d'以外其它字符

正则表达式符号的说明:

Regular Expression Operators
a?  matches 
0  or  1  occurrence of *a*  'a' or empty string  
a*  matches 
0  or more occurrences of *a*  empty string or 'a' ,  'aa' ,  'aaa' ,  etc  
a+  matches 
1  or more occurrences of *a*  'a' ,  'aa' ,  'aaa' ,  etc  
a|b  match *a* or *b*  'a' or 'b' -  
.  match any single character  'a'
,  'q' ,  'l' ,  '_' ,  '+' ,  etc  
[ woeirjsd ]   match any of the named characters  'w' ,  'o' ,  'e' ,  'i' ,  'r' ,  'j' ,  's' ,  'd'  
[ 1-9 ]   match any of the characters in the range  ' 1 ' ,  ' 2 ' ,  ' 3 ' ,  ' 4 ' ,  ' 5 ' ,  ' 6 ' ,  ' 7 ' ,  ' 8 ' ,  ' 9 '  
[ ^13579 ]   match any characters not named  even digits ,  or any other character  
(ie)  group an expression (for use with other operators)  'ie'  
^a  match an *a* at the beginning of a line  'a'  
a$  match an *a* at the end of a line  'a'  

有件事情你是必须知道的,假如你想匹配一个上面有特殊意思的符号,比如?,
你必须在?前面加'\'进行转义.

我们来看看这个例子:
check( " I love beijing? " , / [ ^\? ] +\?/)
这可能是你遇到的第一个难看的正则.然而这种情况在Perl语言里面是
经常出现的.
遇到这种情况,我们可以把规则拆开开看:
/         正则开始
[^\?]   不能是?号
+         出现一次或多次
\?         匹配?
/          正则结束

这样的话,这个正则就很清楚了.
输出为: true.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值