Return type | Name and parameters |
---|---|
boolean
|
asBoolean()
Coerce a string (an instance of CharSequence) to a boolean value. |
Object
|
asType(Class c)
Provides a method to perform custom 'dynamic' type conversion
to the given class using the |
Pattern
|
bitwiseNegate()
Turns a CharSequence into a regular expression Pattern |
String
|
capitalize()
Convenience method to capitalize the first letter of a CharSequence (typically the first letter of a word). |
String
|
center(Number numberOfChars)
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character around it as many times as needed so that it remains centered. |
String
|
center(Number numberOfChars, CharSequence padding)
Pad a CharSequence to a minimum length specified by numberOfChars, appending the supplied padding CharSequence around the original as many times as needed keeping it centered. |
boolean
|
contains(CharSequence text)
Provide an implementation of contains() like Collection#contains(Object) to make CharSequences more polymorphic. |
int
|
count(CharSequence text)
Count the number of occurrences of a sub CharSequence. |
String
|
denormalize()
Return a CharSequence with lines (separated by LF, CR/LF, or CR) terminated by the platform specific line separator. |
CharSequence
|
drop(int num)
Drops the given number of chars from the head of this CharSequence if they are available. |
CharSequence
|
dropWhile(Closure condition)
Create a suffix of the given CharSequence by dropping as many characters as possible from the front of the original CharSequence such that calling the given closure condition evaluates to true when passed each of the dropped characters. |
Object
|
eachLine(Closure closure)
Iterates through this CharSequence line by line. |
Object
|
eachLine(int firstLine, Closure closure)
Iterates through this CharSequence line by line. |
Object
|
eachMatch(CharSequence regex, Closure closure)
Process each regex group matched substring of the given CharSequence. |
Object
|
eachMatch(Pattern pattern, Closure closure)
Process each regex group matched substring of the given pattern. |
String
|
expand()
Expands all tabs into spaces with tabStops of size 8. |
String
|
expand(int tabStop)
Expands all tabs into spaces. |
String
|
expandLine(int tabStop)
Expands all tabs into spaces. |
String
|
find(CharSequence regex)
Finds the first occurrence of a regular expression String within a String. |
String
|
find(CharSequence regex, Closure closure)
Returns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence. |
String
|
find(Pattern pattern)
Finds the first occurrence of a compiled regular expression Pattern within a String. |
String
|
find(Pattern pattern, Closure closure)
Returns the result of calling a closure with the first occurrence of a compiled regular expression found within a String. |
List
|
findAll(CharSequence regex)
Returns a (possibly empty) list of all occurrences of a regular expression (provided as a CharSequence) found within a CharSequence. |
List
|
findAll(CharSequence regex, Closure closure)
Finds all occurrences of a regular expression string within a CharSequence. |
List
|
findAll(Pattern pattern)
Returns a (possibly empty) list of all occurrences of a regular expression (in Pattern format) found within a CharSequence. |
List
|
findAll(Pattern pattern, Closure closure)
Finds all occurrences of a compiled regular expression Pattern within a CharSequence. |
String
|
getAt(EmptyRange range)
Support the range subscript operator for CharSequence or StringBuffer with EmptyRange |
CharSequence
|
getAt(IntRange range)
Support the range subscript operator for CharSequence with IntRange |
CharSequence
|
getAt(Range range)
Support the range subscript operator for CharSequence |
CharSequence
|
getAt(int index)
Support the subscript operator for CharSequence. |
String
|
getAt(Collection indices)
Select a List of characters from a CharSequence using a Collection to identify the indices to be selected. |
char[]
|
getChars()
Converts the given CharSequence into an array of characters. |
boolean
|
isAllWhitespace()
True if a CharSequence only contains whitespace characters. |
boolean
|
isBigDecimal()
Determine if a CharSequence can be parsed as a BigDecimal. |
boolean
|
isBigInteger()
Determine if a CharSequence can be parsed as a BigInteger. |
boolean
|
isCase(Object switchValue)
'Case' implementation for a CharSequence, which uses equals between the toString() of the caseValue and the switchValue. |
boolean
|
isDouble()
Determine if a CharSequence can be parsed as a Double. |
boolean
|
isFloat()
Determine if a CharSequence can be parsed as a Float. |
boolean
|
isInteger()
Determine if a CharSequence can be parsed as an Integer. |
boolean
|
isLong()
Determine if a CharSequence can be parsed as a Long. |
boolean
|
isNumber()
Determine if a CharSequence can be parsed as a Number. |
StringBuilder
|
leftShift(Object value)
Overloads the left shift operator to provide an easy way to append multiple objects as string representations to a CharSequence. |
boolean
|
matches(Pattern pattern)
Tells whether or not a CharSequence matches the given compiled regular expression Pattern. |
String
|
minus(Object target)
Remove a part of a CharSequence by replacing the first occurrence of target within self with '' and returns the result. |
String
|
minus(Pattern pattern)
Remove a part of a CharSequence. |
String
|
multiply(Number factor)
Repeat a CharSequence a certain number of times. |
String
|
next()
This method is called by the ++ operator for the class CharSequence. |
String
|
normalize()
Return a String with linefeeds and carriage returns normalized to linefeeds. |
String
|
padLeft(Number numberOfChars)
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the left as many times as needed. |
String
|
padLeft(Number numberOfChars, CharSequence padding)
Pad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the left. |
String
|
padRight(Number numberOfChars)
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the right as many times as needed. |
String
|
padRight(Number numberOfChars, CharSequence padding)
Pad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the right. |
String
|
plus(Object value)
Appends the String representation of the given operand to this CharSequence. |
String
|
previous()
This method is called by the -- operator for the class CharSequence. |
List
|
readLines()
Return the lines of a CharSequence as a List of String. |
String
|
replaceAll(CharSequence regex, Closure closure)
Replaces all occurrences of a captured group by the result of a closure on that text. |
String
|
replaceAll(CharSequence regex, CharSequence replacement)
Replaces each substring of this CharSequence that matches the given regular expression with the given replacement. |
String
|
replaceAll(Pattern pattern, Closure closure)
Replaces all occurrences of a captured group by the result of a closure call on that text. |
String
|
replaceAll(Pattern pattern, CharSequence replacement)
Replaces all substrings of a CharSequence that match the given compiled regular expression with the given replacement. |
String
|
replaceFirst(CharSequence regex, Closure closure)
Replaces the first occurrence of a captured group by the result of a closure call on that text. |
String
|
replaceFirst(CharSequence regex, CharSequence replacement)
Replaces the first substring of this CharSequence that matches the given regular expression with the given replacement. |
String
|
replaceFirst(Pattern pattern, Closure closure)
Replaces the first occurrence of a captured group by the result of a closure call on that text. |
String
|
replaceFirst(Pattern pattern, CharSequence replacement)
Replaces the first substring of a CharSequence that matches the given compiled regular expression with the given replacement. |
String
|
reverse()
Creates a String which is the reverse (backwards) of this CharSequence |
int
|
size()
Provide the standard Groovy size() method for CharSequence .
|
String[]
|
split()
Convenience method to split a CharSequence (with whitespace as delimiter). |
Object
|
splitEachLine(CharSequence regex, Closure closure)
Iterates through the given CharSequence line by line, splitting each line using the given regex delimiter. |
Object
|
splitEachLine(Pattern pattern, Closure closure)
Iterates through the given CharSequence line by line, splitting each line using the given separator Pattern. |
String
|
stripIndent()
Strip leading spaces from every line in a CharSequence. |
String
|
stripIndent(int numChars)
Strip numChar leading characters from every line in a CharSequence. |
String
|
stripMargin()
Strip leading whitespace/control characters followed by '|' from every line in a CharSequence. |
String
|
stripMargin(char marginChar)
Strip leading whitespace/control characters followed by marginChar from every line in a CharSequence. |
String
|
stripMargin(CharSequence marginChar)
Strip leading whitespace/control characters followed by marginChar from every line in a CharSequence. |
CharSequence
|
take(int num)
Returns the first num elements from this CharSequence.
|
CharSequence
|
takeWhile(Closure condition)
Returns the longest prefix of this CharSequence where each element passed to the given closure evaluates to true. |
BigDecimal
|
toBigDecimal()
Parse a CharSequence into a BigDecimal |
BigInteger
|
toBigInteger()
Parse a CharSequence into a BigInteger |
Double
|
toDouble()
Parse a CharSequence into a Double |
Float
|
toFloat()
Parse a CharSequence into a Float |
Integer
|
toInteger()
Parse a CharSequence into an Integer |
List
|
toList()
Converts the given CharSequence into a List of Strings of one character. |
Long
|
toLong()
Parse a CharSequence into a Long |
Set
|
toSet()
Converts the given CharSequence into a Set of unique String of one character. |
Short
|
toShort()
Parse a CharSequence into a Short |
URI
|
toURI()
Transforms a CharSequence representing a URI into a URI object. |
URL
|
toURL()
Transforms a CharSequence representing a URL into a URL object. |
List
|
tokenize()
Tokenize a CharSequence (with a whitespace as the delimiter). |
List
|
tokenize(CharSequence token)
Tokenize a CharSequence based on the given CharSequence delimiter. |
List
|
tokenize(Character token)
Tokenize a CharSequence based on the given character delimiter. |
String
|
tr(CharSequence sourceSet, CharSequence replacementSet)
Translates a CharSequence by replacing characters from the sourceSet with characters from replacementSet. |
String
|
unexpand()
Replaces sequences of whitespaces with tabs using tabStops of size 8. |
String
|
unexpand(int tabStop)
Replaces sequences of whitespaces with tabs. |
String
|
unexpandLine(int tabStop)
Replaces sequences of whitespaces with tabs within a line. |
Coerce a string (an instance of CharSequence) to a boolean value. A string is coerced to false if it is of length 0, and to true otherwise.
Provides a method to perform custom 'dynamic' type conversion
to the given class using the as
operator.
c
- the desired classTurns a CharSequence into a regular expression Pattern
Convenience method to capitalize the first letter of a CharSequence (typically the first letter of a word). Example usage:
assert 'h'.capitalize() == 'H' assert 'hello'.capitalize() == 'Hello' assert 'hello world'.capitalize() == 'Hello world' assert 'Hello World' == 'hello world'.split(' ').collect{ it.capitalize() }.join(' ')
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character around it as many times as needed so that it remains centered. If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example:
['A', 'BB', 'CCC', 'DDDD'].each{ println '|' + it.center(6) + '|' }will produce output like:
| A | | BB | | CCC | | DDDD |
numberOfChars
- the total minimum number of characters of the resultPad a CharSequence to a minimum length specified by numberOfChars, appending the supplied padding CharSequence around the original as many times as needed keeping it centered. If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example:
['A', 'BB', 'CCC', 'DDDD'].each{ println '|' + it.center(6, '+') + '|' }will produce output like:
|++A+++| |++BB++| |+CCC++| |+DDDD+|
numberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for paddingProvide an implementation of contains() like Collection#contains(Object) to make CharSequences more polymorphic.
text
- the CharSequence to look forCount the number of occurrences of a sub CharSequence.
text
- a sub CharSequenceReturn a CharSequence with lines (separated by LF, CR/LF, or CR) terminated by the platform specific line separator.
Drops the given number of chars from the head of this CharSequence if they are available.
def text = "Groovy" assert text.drop( 0 ) == 'Groovy' assert text.drop( 2 ) == 'oovy' assert text.drop( 7 ) == ''
num
- the number of characters to drop from this iteratornum
ones,
or else an empty String, if this CharSequence has less than num
characters.Create a suffix of the given CharSequence by dropping as many characters as possible from the front of the original CharSequence such that calling the given closure condition evaluates to true when passed each of the dropped characters.
def text = "Groovy" assert text.dropWhile{ false } == 'Groovy' assert text.dropWhile{ true } == '' assert text.dropWhile{ it < 'Z' } == 'roovy' assert text.dropWhile{ it != 'v' } == 'vy'
condition
- the closure that while continuously evaluating to true will cause us to drop elements from
the front of the original CharSequenceIterates through this CharSequence line by line. Each line is passed to the given 1 or 2 arg closure. If a 2 arg closure is found the line count is passed as the second argument.
closure
- a closureIterates through this CharSequence line by line. Each line is passed to the given 1 or 2 arg closure. If a 2 arg closure is found the line count is passed as the second argument.
firstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure (arg 1 is line, optional arg 2 is line number)Process each regex group matched substring of the given CharSequence. If the closure parameter takes one argument, an array with all match groups is passed to it. If the closure takes as many arguments as there are match groups, then each parameter will be one match group.
regex
- a Regex CharSequenceclosure
- a closure with one parameter or as much parameters as groupsProcess each regex group matched substring of the given pattern. If the closure parameter takes one argument, an array with all match groups is passed to it. If the closure takes as many arguments as there are match groups, then each parameter will be one match group.
pattern
- a regex Patternclosure
- a closure with one parameter or as much parameters as groupsExpands all tabs into spaces with tabStops of size 8.
Expands all tabs into spaces. If the CharSequence has multiple lines, expand each line - restarting tab stops at the start of each line.
tabStop
- The number of spaces a tab representsExpands all tabs into spaces. Assumes the CharSequence represents a single line of text.
tabStop
- The number of spaces a tab representsFinds the first occurrence of a regular expression String within a String. If the regex doesn't match, null will be returned.
For example, if the regex doesn't match the result is null:
assert null == "New York, NY".find(/\d{5}/)If it does match, we get the matching string back:
assert "10292" == "New York, NY 10292-0098".find(/\d{5}/)If we have capture groups in our expression, we still get back the full match
assert "10292-0098" == "New York, NY 10292-0098".find(/(\d{5})-?(\d{4})/)
regex
- the capturing regexReturns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence. If the regex doesn't match, the closure will not be called and find will return null.
regex
- the capturing regex CharSequenceclosure
- the closure that will be passed the full match, plus each of the capturing groups (if any)Finds the first occurrence of a compiled regular expression Pattern within a String. If the pattern doesn't match, null will be returned.
For example, if the pattern doesn't match the result is null:
assert null == "New York, NY".find(~/\d{5}/)If it does match, we get the matching string back:
assert "10292" == "New York, NY 10292-0098".find(~/\d{5}/)If we have capture groups in our expression, the groups are ignored and we get back the full match:
assert "10292-0098" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/)If you need to work with capture groups, then use the closure version of this method or use Groovy's matcher operators or use eachMatch.
pattern
- the compiled regex PatternReturns the result of calling a closure with the first occurrence of a compiled regular expression found within a String. If the regex doesn't match, the closure will not be called and find will return null.
For example, if the pattern doesn't match, the result is null:
assert null == "New York, NY".find(~/\d{5}/) { match -> return "-$match-"}If it does match and we don't have any capture groups in our regex, there is a single parameter on the closure that the match gets passed to:
assert "-10292-" == "New York, NY 10292-0098".find(~/\d{5}/) { match -> return "-$match-"}If we have capture groups in our expression, our closure has one parameter for the match, followed by one for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour -> assert match == "10292-0098" assert zip == "10292" assert plusFour == "0098" return zip }If we have capture groups in our expression, and our closure has one parameter, the closure will be passed an array with the first element corresponding to the whole match, followed by an element for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour -> assert array[0] == "10292-0098" assert array[1] == "10292" assert array[2] == "0098" return array[1] }If a capture group is optional, and doesn't match, then the corresponding value for that capture group passed to the closure will be null as illustrated here:
assert "2339999" == "adsf 233-9999 adsf".find(~/(\d{3})?-?(\d{3})-(\d{4})/) { match, areaCode, exchange, stationNumber -> assert "233-9999" == match assert null == areaCode assert "233" == exchange assert "9999" == stationNumber return "$exchange$stationNumber" }
pattern
- the compiled regex Patternclosure
- the closure that will be passed the full match, plus each of the capturing groups (if any)Returns a (possibly empty) list of all occurrences of a regular expression (provided as a CharSequence) found within a CharSequence.
For example, if the regex doesn't match, it returns an empty list:
assert [] == "foo".findAll(/(\w*) Fish/)Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned:
def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"] assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(/(\w*) Fish/)If you need to work with capture groups, then use the closure version of this method or use Groovy's matcher operators or use eachMatch.
regex
- the capturing regex CharSequenceFinds all occurrences of a regular expression string within a CharSequence. Any matches are passed to the specified closure. The closure is expected to have the full match in the first parameter. If there are any capture groups, they will be placed in subsequent parameters.
If there are no matches, the closure will not be called, and an empty List will be returned.
For example, if the regex doesn't match, it returns an empty list:
assert [] == "foo".findAll(/(\w*) Fish/) { match, firstWord -> return firstWord }Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match:
assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(/.ould/) { match -> "${match}n't"}If there are capture groups, the first parameter will be the match followed by one parameter for each capture group:
def orig = "There's a Wocket in my Pocket" assert ["W > Wocket", "P > Pocket"] == orig.findAll(/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
regex
- the capturing regex CharSequenceclosure
- will be passed the full match plus each of the capturing groups (if any)Returns a (possibly empty) list of all occurrences of a regular expression (in Pattern format) found within a CharSequence.
For example, if the pattern doesn't match, it returns an empty list:
assert [] == "foo".findAll(~/(\w*) Fish/)Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned:
def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"] assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(~/(\w*) Fish/)
pattern
- the compiled regex PatternFinds all occurrences of a compiled regular expression Pattern within a CharSequence. Any matches are passed to the specified closure. The closure is expected to have the full match in the first parameter. If there are any capture groups, they will be placed in subsequent parameters.
If there are no matches, the closure will not be called, and an empty List will be returned.
For example, if the pattern doesn't match, it returns an empty list:
assert [] == "foo".findAll(~/(\w*) Fish/) { match, firstWord -> return firstWord }Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match:
assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(~/.ould/) { match -> "${match}n't"}If there are capture groups, the first parameter will be the match followed by one parameter for each capture group:
def orig = "There's a Wocket in my Pocket" assert ["W > Wocket", "P > Pocket"] == orig.findAll(~/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
pattern
- the compiled regex Patternclosure
- will be passed the full match plus each of the capturing groups (if any)Support the range subscript operator for CharSequence or StringBuffer with EmptyRange
range
- an EmptyRangeSupport the range subscript operator for CharSequence with IntRange
range
- an IntRangeSupport the range subscript operator for CharSequence
range
- a RangeSupport the subscript operator for CharSequence.
index
- the index of the Character to getSelect a List of characters from a CharSequence using a Collection to identify the indices to be selected.
indices
- a Collection of indicesConverts the given CharSequence into an array of characters.
True if a CharSequence only contains whitespace characters.
Determine if a CharSequence can be parsed as a BigDecimal.
Determine if a CharSequence can be parsed as a BigInteger.
'Case' implementation for a CharSequence, which uses equals between the toString() of the caseValue and the switchValue. This allows CharSequence values to be used in switch statements. For example:
switch( str ) { case 'one' : // etc... }Note that this returns
true
for the case where both the
'switch' and 'case' operand is null
.
switchValue
- the switch valueDetermine if a CharSequence can be parsed as a Double.
Determine if a CharSequence can be parsed as a Float.
Determine if a CharSequence can be parsed as an Integer.
Determine if a CharSequence can be parsed as a Long.
Determine if a CharSequence can be parsed as a Number. Synonym for 'isBigDecimal()'.
Overloads the left shift operator to provide an easy way to append multiple objects as string representations to a CharSequence.
value
- an ObjectTells whether or not a CharSequence matches the given compiled regular expression Pattern.
pattern
- the regex Pattern to which the string of interest is to be matchedRemove a part of a CharSequence by replacing the first occurrence of target within self with '' and returns the result.
target
- an object representing the part to removeRemove a part of a CharSequence. This replaces the first occurrence of the pattern within self with '' and returns the result.
pattern
- a Pattern representing the part to removeRepeat a CharSequence a certain number of times.
factor
- the number of times the CharSequence should be repeatedThis method is called by the ++ operator for the class CharSequence. It increments the last character in the given CharSequence. If the last character in the CharSequence is Character.MAX_VALUE a Character.MIN_VALUE will be appended. The empty CharSequence is incremented to a string consisting of the character Character.MIN_VALUE.
Return a String with linefeeds and carriage returns normalized to linefeeds.
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the left as many times as needed. If the String is already the same size or bigger than the target numberOfChars, then the original String is returned. An example:
println 'Numbers:' [1, 10, 100, 1000].each{ println it.toString().padLeft(5) }will produce output like:
Numbers: 1 10 100 1000
numberOfChars
- the total minimum number of characters of the resulting CharSequencePad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the left. If the CharSequence is already the same size or bigger than the target numberOfChars, then the toString() of the original CharSequence is returned. An example:
println 'Numbers:' [1, 10, 100, 1000].each{ println it.toString().padLeft(5, '*') } [2, 20, 200, 2000].each{ println it.toString().padLeft(5, '*_') }will produce output like:
Numbers: ****1 ***10 **100 *1000 *_*_2 *_*20 *_200 *2000
numberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for paddingPad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the right as many times as needed. If the CharSequence is already the same size or bigger than the target numberOfChars, then the toString() of the original CharSequence is returned. An example:
['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5) + it.size() }will produce output like:
A 1 BB 2 CCC 3 DDDD 4
numberOfChars
- the total minimum number of characters of the resulting stringPad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the right. If the CharSequence is already the same size or bigger than the target numberOfChars, then the toString() of the original CharSequence is returned. An example:
['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5, '#') + it.size() }will produce output like:
A####1 BB###2 CCC##3 DDDD#4
numberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for paddingAppends the String representation of the given operand to this CharSequence.
value
- any ObjectThis method is called by the -- operator for the class CharSequence. It decrements the last character in the given CharSequence. If the last character in the CharSequence is Character.MIN_VALUE it will be deleted. The empty CharSequence can't be decremented.
Return the lines of a CharSequence as a List of String.
Replaces all occurrences of a captured group by the result of a closure on that text.
For examples,
assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() } assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() }) Here, it[0] is the global string of the matched group it[1] is the first string in the matched group it[2] is the second string in the matched group assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() }) Here, x is the global string of the matched group y is the first string in the matched group z is the second string in the matched groupNote that unlike String.replaceAll(String regex, String replacement), where the replacement string treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string and that value is used literally for the replacement.
regex
- the capturing regexclosure
- the closure to apply on each captured groupReplaces each substring of this CharSequence that matches the given regular expression with the given replacement.
regex
- the capturing regexreplacement
- the string to be substituted for each matchReplaces all occurrences of a captured group by the result of a closure call on that text.
For examples,
assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() } assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { it[0].toUpperCase() }) Here, it[0] is the global string of the matched group it[1] is the first string in the matched group it[2] is the second string in the matched group assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() }) Here, it[0] is the global string of the matched group it[1] is the first string in the matched group it[2] is the second string in the matched group assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() }) Here, x is the global string of the matched group y is the first string in the matched group z is the second string in the matched groupNote that unlike String.replaceAll(String regex, String replacement), where the replacement string treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string and that value is used literally for the replacement.
pattern
- the capturing regex Patternclosure
- the closure to apply on each captured groupReplaces all substrings of a CharSequence that match the given compiled regular expression with the given replacement.
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher#replaceAll. Use Matcher#quoteReplacement to suppress the special meaning of these characters, if desired.
assert "foo".replaceAll('o', 'X') == 'fXX'
pattern
- the regex Pattern to which the CharSequence of interest is to be matchedreplacement
- the CharSequence to be substituted for the first matchReplaces the first occurrence of a captured group by the result of a closure call on that text.
For example (with some replaceAll variants thrown in for comparison purposes),
assert "hellO world" == "hello world".replaceFirst("(o)") { it[0].toUpperCase() } // first match assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() } // all matches assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
regex
- the capturing regexclosure
- the closure to apply on the first captured groupReplaces the first substring of this CharSequence that matches the given regular expression with the given replacement.
regex
- the capturing regexreplacement
- the CharSequence to be substituted for each matchReplaces the first occurrence of a captured group by the result of a closure call on that text.
For example (with some replaceAll variants thrown in for comparison purposes),
assert "hellO world" == "hello world".replaceFirst(~"(o)") { it[0].toUpperCase() } // first match assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() } // all matches assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
pattern
- the capturing regex Patternclosure
- the closure to apply on the first captured groupReplaces the first substring of a CharSequence that matches the given compiled regular expression with the given replacement.
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher#replaceFirst. Use Matcher#quoteReplacement to suppress the special meaning of these characters, if desired.
assert "foo".replaceFirst('o', 'X') == 'fXo'
pattern
- the regex Pattern to which the CharSequence of interest is to be matchedreplacement
- the CharSequence to be substituted for the first matchCreates a String which is the reverse (backwards) of this CharSequence
Provide the standard Groovy size()
method for CharSequence
.
Convenience method to split a CharSequence (with whitespace as delimiter). Similar to tokenize, but returns an Array of String instead of a List.
Iterates through the given CharSequence line by line, splitting each line using the given regex delimiter. The list of tokens for each line is then passed to the given closure.
regex
- the delimiting regular expressionclosure
- a closureIterates through the given CharSequence line by line, splitting each line using the given separator Pattern. The list of tokens for each line is then passed to the given closure.
pattern
- the regular expression Pattern for the delimiterclosure
- a closureStrip leading spaces from every line in a CharSequence. The line with the least number of leading spaces determines the number to remove. Lines only containing whitespace are ignored when calculating the number of leading spaces to strip.
assert ' A\n B\nC' == ' A\n B\n C'.stripIndent()
Strip numChar leading characters from every line in a CharSequence.
assert 'DEF\n456' == '''ABCDEF\n123456'''.stripIndent(3)
numChars
- The number of characters to stripStrip leading whitespace/control characters followed by '|' from every line in a CharSequence.
assert 'ABC\n123\n456' == '''ABC |123 |456'''.stripMargin()
Strip leading whitespace/control characters followed by marginChar from every line in a CharSequence.
assert 'ABC\n123\n456' == '''ABC *123 *456'''.stripMargin('*')
marginChar
- Any character that serves as margin delimiterStrip leading whitespace/control characters followed by marginChar from every line in a CharSequence.
marginChar
- Any character that serves as margin delimiterReturns the first num
elements from this CharSequence.
def text = "Groovy" assert text.take( 0 ) == '' assert text.take( 2 ) == 'Gr' assert text.take( 7 ) == 'Groovy'
num
- the number of chars to take from this CharSequencenum
chars,
or else the whole CharSequence if it has less then num
elements.Returns the longest prefix of this CharSequence where each element passed to the given closure evaluates to true.
def text = "Groovy" assert text.takeWhile{ it < 'A' } == '' assert text.takeWhile{ it < 'Z' } == 'G' assert text.takeWhile{ it != 'v' } == 'Groo' assert text.takeWhile{ it < 'z' } == 'Groovy'
condition
- the closure that must evaluate to true to continue taking elementsParse a CharSequence into a BigDecimal
Parse a CharSequence into a BigInteger
Parse a CharSequence into a Double
Parse a CharSequence into a Float
Parse a CharSequence into an Integer
Converts the given CharSequence into a List of Strings of one character.
Parse a CharSequence into a Long
Converts the given CharSequence into a Set of unique String of one character.
Parse a CharSequence into a Short
Transforms a CharSequence representing a URI into a URI object.
Transforms a CharSequence representing a URL into a URL object.
Tokenize a CharSequence (with a whitespace as the delimiter).
Tokenize a CharSequence based on the given CharSequence delimiter.
token
- the delimiterTokenize a CharSequence based on the given character delimiter. For example:
char pathSep = ':' assert "/tmp:/usr".tokenize(pathSep) == ["/tmp", "/usr"]
token
- the delimiterTranslates a CharSequence by replacing characters from the sourceSet with characters from replacementSet. If the first character from sourceSet appears in the CharSequence, it will be replaced with the first character from replacementSet. If the second character from sourceSet appears in the CharSequence, it will be replaced with the second character from replacementSet. and so on for all provided replacement characters.
Here is an example which converts the vowels in a word from lower to uppercase:
assert 'hello'.tr('aeiou', 'AEIOU') == 'hEllO'A character range using regex-style syntax can also be used, e.g. here is an example which converts a word from lower to uppercase:
assert 'hello'.tr('a-z', 'A-Z') == 'HELLO'Hyphens at the start or end of sourceSet or replacementSet are treated as normal hyphens and are not considered to be part of a range specification. Similarly, a hyphen immediately after an earlier range is treated as a normal hyphen. So, '-x', 'x-' have no ranges while 'a-c-e' has the range 'a-c' plus the '-' character plus the 'e' character.
Unlike the unix tr command, Groovy's tr command supports reverse ranges, e.g.:
assert 'hello'.tr('z-a', 'Z-A') == 'HELLO'If replacementSet is smaller than sourceSet, then the last character from replacementSet is used as the replacement for all remaining source characters as shown here:
assert 'Hello World!'.tr('a-z', 'A') == 'HAAAA WAAAA!'If sourceSet contains repeated characters, the last specified replacement is used as shown here:
assert 'Hello World!'.tr('lloo', '1234') == 'He224 W4r2d!'The functionality provided by tr can be achieved using regular expressions but tr provides a much more compact notation and efficient implementation for certain scenarios.
sourceSet
- the set of characters to translate fromreplacementSet
- the set of replacement charactersReplaces sequences of whitespaces with tabs using tabStops of size 8.
Replaces sequences of whitespaces with tabs.
tabStop
- The number of spaces a tab representsReplaces sequences of whitespaces with tabs within a line.
tabStop
- The number of spaces a tab represents