Groovy字符串很groovy

字符串定义:
1.''  //一般字符串,不解析表达式
eg:
def mess = 'Hello.'
'I say ${mess}'  //Result: "I say ${mess}"
2.""  //一般字符串,解析表达式
eg:
def mess = 'Hello.'
"I say ${mess}"  //Result: "I say Hello."
3.
'''
'''和
"""
"""  //段落字符,单引号不解析表达式,双引号解析表达式
eg:
def sqlQuery = '''
    SELECT id
    FROM table
    WHERE 1=1
'''

字符串索引:
def mess = 'Hello World'
mess[2..7]    //Result: "llo Wo"
mess[2..<7]   //Result: "llo W"
mess[2]       //Result: "l"
mess[2,6]     //Result: "lW"

字符串操作:
mess - 'rld'    //Result: "Hello Wo"
mess*3          //Result: "Hello WorldHello WorldHello World"
'?'*5           //Result: "?????"
mess << ' Yeah' //Result: Hello World Yeah

字符串方法(部分方法):
def mess = 'Hello World'
mess.count('o')       //Result: 2;计算指定字符出现次数
mess.size()           //Result: 11;和length()方法一样
mess.length()         //Result: 11
mess.contains('orl')  //Result: true
mess.center(18)       //Result: "   Hello World    ";如果字符数量小于指定参数,则两边补空格
mess.center(18,'*')   //Result: "***Hello World****";如果字符数量小于指定参数,则两边补第二个参数
mess.reverse()        //Result: "dlroW olleH"
'Hello'.toList()      //Result: ["H", "e", "l", "l", "o"]
mess.padLeft(15)      //Result: "    Hello World"
mess.padLeft(15,'#')  //Result: "####Hello World"
mess.padRight(15)     //Result: "Hello World    "
mess.padRight(15,'#') //Result: "Hello World####"
mess.getAt(2..5)      //Result: "llo "
mess.getAt([2,6])     //Result: "lW"

字符串比较:
'abc' == 'abc'          //Result: true;比较值是否相等
'abc' <=> 'abc'         //Result: 0;和
'abc' <=> 'abf'         //Result: -1
'abc' <=> 'Abf'         //Result: 1
'abc'.compareTo('abc')  //Result: 0
'abc'.compareTo('abf')  //Result: -3
'abc'.compareTo('Abf')  //Result: 32

find方法,支持表达式:
def s = 'abcdefg'
s.find('bc.?') //bcd
s.find('bc.*') //bcdefg
s.find('bc.*e') //bcde

正则表达式:
使用=~ 'regex’表示正则表达式
'abc' ==~ '^.?bc'  //Result: true

你可能感兴趣的:(正则表达式,groovy)