public class StringGroovyMethods extends DefaultGroovyMethodsSupport
This class defines new groovy methods which appear on String-related JDK
classes (String, CharSequence, Matcher) inside the Groovy environment.
Static methods are used with the first parameter being the destination class,
e.g. public static String reverse(String self)
provides a reverse()
method for String
.
NOTE: While this class contains many 'public' static methods, it is primarily regarded as an internal class (its internal package name suggests this also). We value backwards compatibility of these methods when used within Groovy but value less backwards compatibility at the Java method call level. I.e. future versions of Groovy may remove or move a method call in this file but would normally aim to keep the method available from within Groovy.
Type Params | Return Type | Name and description |
---|---|---|
|
public static boolean |
asBoolean(CharSequence chars) Coerces a CharSequence to a boolean value. |
|
public static boolean |
asBoolean(Matcher matcher) Coerces a Matcher instance to a boolean value. |
<T> |
public static T |
asType(CharSequence self, Class<T> c) Provides a method to perform custom 'dynamic' type conversion to the given class using the as operator. |
<T> |
public static T |
asType(GString self, Class<T> c) Converts the GString to a File, or delegates to the default DefaultGroovyMethods.asType. |
<T> |
public static T |
asType(String self, Class<T> c) Provides a method to perform custom 'dynamic' type conversion to the given class using the as operator. |
|
public static Pattern |
bitwiseNegate(CharSequence self) Turns a CharSequence into a regular expression Pattern. |
|
public static String |
capitalize(CharSequence self) Convenience method to capitalize the first letter of a CharSequence (typically the first letter of a word). |
|
public static String |
center(CharSequence self, Number numberOfChars) Pads 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. |
|
public static String |
center(CharSequence self, 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. |
|
public static String |
collectReplacements(String self, Closure<String> transform) Iterates through this String a character at a time collecting either the original character or a transformed replacement String. |
|
public static String |
collectReplacements(String self, List<Function<Character, Optional<String>>> transforms) Iterates through this String a character at a time collecting either the original character or a transformed replacement String. |
|
public static boolean |
contains(CharSequence self, CharSequence text) Provides an implementation of contains() like Collection.contains to make CharSequences more polymorphic. |
|
public static boolean |
containsIgnoreCase(CharSequence self, CharSequence searchString) Checks whether this CharSequence contains the searchString ignoring the caseConsiderations. |
|
public static int |
count(CharSequence self, CharSequence text) Counts the number of occurrences of a sub CharSequence. |
|
public static String |
denormalize(CharSequence self) Return a CharSequence with lines (separated by LF, CR/LF, or CR) terminated by the platform specific line separator. |
|
public static CharSequence |
drop(CharSequence self, int num) Drops the given number of chars from the head of this CharSequence if they are available. |
|
public static String |
drop(GString self, int num) A GString variant of the equivalent CharSequence method. |
|
public static String |
drop(String self, int num) A String variant of the equivalent CharSequence method. |
|
public static CharSequence |
dropRight(CharSequence self, int num) Returns new CharSequence after removing the right num chars.
|
|
public static String |
dropRight(String self, int num) A String variant of the equivalent CharSequence method dropRight(CharSequence,int). |
|
public static String |
dropRight(GString self, int num) A GString variant of the equivalent CharSequence method dropRight(CharSequence,int). |
|
public static String |
dropWhile(CharSequence self, Closure condition) Creates 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. |
|
public static String |
dropWhile(GString self, Closure condition) A GString variant of the equivalent CharSequence method. |
|
public static CharSequence |
dropWhile$$bridge(CharSequence self, Closure condition) |
<T> |
public static T |
eachLine(CharSequence self, Closure<T> closure) Iterates through this CharSequence line by line. |
<T> |
public static T |
eachLine(CharSequence self, int firstLine, Closure<T> closure) Iterates through this CharSequence line by line. |
<T extends CharSequence> |
public static T |
eachMatch(T self, CharSequence regex, Closure closure) Processes each regex group matched substring of the given CharSequence. |
<T extends CharSequence> |
public static T |
eachMatch(T self, Pattern pattern, Closure closure) Processes each regex group matched substring of the given pattern. |
|
public static String |
eachMatch(String self, Pattern pattern, Closure closure) Processes each regex group matched substring of the given pattern. |
|
public static String |
eachMatch(String self, String regex, Closure closure) Process each regex group matched substring of the given string. |
|
public static boolean |
endsWithAny(CharSequence self, CharSequence suffixes) Tests if this CharSequence ends with any specified suffixes. |
|
public static boolean |
endsWithIgnoreCase(CharSequence self, CharSequence searchString) Checks whether this CharSequence ends with the searchString ignoring the case considerations. |
|
public static String |
expand(CharSequence self) Expands all tabs into spaces with tabStops of size 8. |
|
public static String |
expand(CharSequence self, int tabStop) Expands all tabs into spaces. |
|
public static String |
expandLine(CharSequence self, int tabStop) Expands all tabs into spaces. |
|
public static String |
find(CharSequence self, CharSequence regex) Finds the first occurrence of a regular expression String within a String. |
|
public static String |
find(CharSequence self, CharSequence regex, Closure closure) Returns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence. |
|
public static String |
find(CharSequence self, Pattern pattern) Finds the first occurrence of a compiled regular expression Pattern within a String. |
|
public static String |
find(CharSequence self, Pattern pattern, Closure closure) Returns the result of calling a closure with the first occurrence of a compiled regular expression found within a String. |
|
public static List<String> |
findAll(CharSequence self, CharSequence regex) Returns a (possibly empty) list of all occurrences of a regular expression (provided as a CharSequence) found within a CharSequence. |
<T> |
public static List<T> |
findAll(CharSequence self, CharSequence regex, Closure<T> closure) Finds all occurrences of a regular expression string within a CharSequence. |
|
public static List<String> |
findAll(CharSequence self, Pattern pattern) Returns a (possibly empty) list of all occurrences of a regular expression (in Pattern format) found within a CharSequence. |
<T> |
public static List<T> |
findAll(CharSequence self, Pattern pattern, Closure<T> closure) Finds all occurrences of a compiled regular expression Pattern within a CharSequence. |
|
public static String |
getAt(CharSequence self, Collection indices) Selects a List of characters from a CharSequence using a Collection to identify the indices to be selected. |
|
public static String |
getAt(CharSequence self, EmptyRange range) Supports the range subscript operator for CharSequence or StringBuffer with EmptyRange |
|
public static CharSequence |
getAt(CharSequence self, int index) Supports the subscript operator for CharSequence. |
|
public static String |
getAt(GString self, int index) Supports the subscript operator for GString. |
|
public static CharSequence |
getAt(CharSequence self, IntRange range) Supports the range subscript operator for CharSequence with IntRange. |
|
public static String |
getAt(GString self, IntRange range) Supports the range subscript operator for GString with IntRange. |
|
public static CharSequence |
getAt(CharSequence self, Range range) Supports the range subscript operator for CharSequence. |
|
public static String |
getAt(GString self, Range range) Supports the range subscript operator for GString. |
|
public static List |
getAt(Matcher self, Collection indices) Selects a List of values from a Matcher using a Collection to identify the indices to be selected. |
|
public static Object |
getAt(Matcher self, int index) Supports the subscript operator, e.g. |
|
public static String |
getAt(String self, int index) Supports the subscript operator for String. |
|
public static String |
getAt(String self, IntRange range) Supports the range subscript operator for String with IntRange. |
|
public static String |
getAt(String self, Range range) Supports the range subscript operator for String. |
|
public static char[] |
getChars(CharSequence self) Converts the given CharSequence into an array of characters. |
|
public static int |
getCount(Matcher self) Finds the number of Strings matched to the given Matcher. |
|
public static boolean |
hasGroup(Matcher self) Checks whether a Matcher contains a group or not. |
|
public boolean |
hasNext() |
|
public static boolean |
isAllWhitespace(CharSequence self) Returns true if a CharSequence only contains whitespace characters. |
|
public static Boolean |
isAtLeast(String left, String right) Compares a String representing a number to another. |
|
public static boolean |
isBigDecimal(CharSequence self) Determines if a CharSequence can be parsed as a BigDecimal. |
|
public static boolean |
isBigInteger(CharSequence self) Determines if a CharSequence can be parsed as a BigInteger. |
|
public static boolean |
isBlank(CharSequence self) Tests if this CharSequence is blank. |
|
public static boolean |
isCase(CharSequence caseValue, Object switchValue) 'Case' implementation for a CharSequence, which uses equals between the toString() of the caseValue and the switchValue. |
|
public static boolean |
isCase(Pattern caseValue, Object switchValue) 'Case' implementation for the Pattern class, which allows testing a String against a number of regular expressions. |
|
public static boolean |
isDouble(CharSequence self) Determines if a CharSequence can be parsed as a Double. |
|
public static boolean |
isFloat(CharSequence self) Determines if a CharSequence can be parsed as a Float. |
|
public static boolean |
isInteger(CharSequence self) Determines if a CharSequence can be parsed as an Integer. |
|
public static boolean |
isLong(CharSequence self) Determines if a CharSequence can be parsed as a Long. |
|
public static boolean |
isNumber(CharSequence self) Determines if a CharSequence can be parsed as a Number. |
|
public static Iterator |
iterator(Matcher self) Returns an Iterator which traverses each match. |
|
public static StringBuilder |
leftShift(CharSequence self, Object value) Overloads the left shift operator to provide an easy way to append multiple objects as string representations to a CharSequence. |
|
public static StringBuffer |
leftShift(String self, Object value) |
|
public static StringBuffer |
leftShift(StringBuffer self, Object value) Overloads the left shift operator to provide an easy way to append multiple objects as string representations to a StringBuffer. |
|
public static StringBuilder |
leftShift(StringBuilder self, Object value) Overloads the left shift operator to provide syntactic sugar for appending to a StringBuilder. |
|
public static boolean |
matches(CharSequence self, Pattern pattern) Determines if a CharSequence matches the given regular expression. |
|
public static boolean |
matchesPartially(Matcher self) Given a matcher that matches a string against a pattern, returns true when the string matches the pattern or if a longer string, could match the pattern. |
|
public static String |
minus(CharSequence self, Object target) Removes a part of a CharSequence by replacing the first occurrence of target within self with empty string and returns the result. |
|
public static String |
minus(CharSequence self, Pattern pattern) Removes a part of a CharSequence. |
|
public static String |
multiply(CharSequence self, Number factor) Repeats a CharSequence a certain number of times. |
|
public Object |
next() |
|
public static String |
next(CharSequence self) Overloads the ++ operator for the class CharSequence.
|
|
public static String |
normalize(CharSequence self) Returns a String with linefeeds and carriage returns normalized to linefeeds. |
|
public static String |
padLeft(CharSequence self, Number numberOfChars) Pads a CharSequence to a minimum length specified by numberOfChars by adding the space character
to the left as many times as needed. |
|
public static String |
padLeft(CharSequence self, Number numberOfChars, CharSequence padding) Pads a CharSequence to a minimum length specified by numberOfChars , adding the supplied
padding CharSequence as many times as needed to the left. |
|
public static String |
padRight(CharSequence self, Number numberOfChars) Pads a CharSequence to a minimum length specified by numberOfChars by adding the space
character to the right as many times as needed. |
|
public static String |
padRight(CharSequence self, Number numberOfChars, CharSequence padding) Pads a CharSequence to a minimum length specified by numberOfChars , adding the supplied padding
CharSequence as many times as needed to the right. |
|
public static String |
plus(CharSequence left, Object right) Appends the String representation of the given operand to this CharSequence. |
|
public static String |
plus(Number left, String right) Appends a String to the string representation of this number. |
|
public static String |
plus(String left, CharSequence right) Appends the String representation of the given operand to this string. |
|
public static String |
plus(StringBuffer left, String right) Appends a String to this StringBuffer. |
|
public static String |
previous(CharSequence self) Overloads the -- operator for the class CharSequence.
|
|
public static void |
putAt(StringBuffer self, EmptyRange range, Object value) Supports the range subscript operator for StringBuffer. |
|
public static void |
putAt(StringBuffer self, IntRange range, Object value) Supports the range subscript operator for StringBuffer. |
|
public static List<String> |
readLines(CharSequence self) Returns the lines of a CharSequence as a List of String. |
|
public void |
remove() |
|
public static String |
replace(CharSequence self, Map<CharSequence, CharSequence> replacements) Replaces all occurrences of replacement CharSequences (supplied via a map) within a provided CharSequence. |
|
public static String |
replace(CharSequence self, int capacity, Map<CharSequence, CharSequence> replacements) Replaces all occurrences of replacement CharSequences (supplied via a map) within a provided CharSequence with control over the internally created StringBuilder's capacity. |
|
public static String |
replaceAll(CharSequence self, CharSequence regex, CharSequence replacement) Replaces each substring of this CharSequence that matches the given regular expression with the given replacement. |
|
public static String |
replaceAll(CharSequence self, CharSequence regex, Closure closure) Replaces all occurrences of a captured group by the result of calling a closure on that text. |
|
public static String |
replaceAll(CharSequence self, Pattern pattern, CharSequence replacement) Replaces all substrings of a CharSequence that match the given compiled regular expression with the given replacement. |
|
public static String |
replaceAll(CharSequence self, Pattern pattern, Closure closure) Replaces all occurrences of a captured group by the result of a closure call on that text. |
|
public static String |
replaceFirst(CharSequence self, CharSequence regex, CharSequence replacement) Replaces the first substring of this CharSequence that matches the given regular expression with the given replacement. |
|
public static String |
replaceFirst(CharSequence self, CharSequence regex, Closure closure) Replaces the first occurrence of a captured group by the result of a closure call on that text. |
|
public static String |
replaceFirst(CharSequence self, Pattern pattern, CharSequence replacement) Replaces the first substring of a CharSequence that matches the given compiled regular expression with the given replacement. |
|
public static String |
replaceFirst(CharSequence self, Pattern pattern, Closure closure) Replaces the first occurrence of a captured group by the result of a closure call on that text. |
|
public static String |
reverse(CharSequence self) Creates a String which is the reverse (backwards) of this CharSequence |
|
public static void |
setIndex(Matcher self, int index) Sets the position of the given Matcher to the given index. |
|
public static int |
size(CharSequence self) Provides the standard Groovy size() method for CharSequence . |
|
public static long |
size(Matcher self) Provides the standard Groovy size() method for Matcher . |
|
public static int |
size(String self) Provides the standard Groovy size() method for String . |
|
public static int |
size(StringBuffer self) Provides the standard Groovy size() method for StringBuffer . |
|
public static String[] |
split(CharSequence self) Splits a CharSequence (with whitespace as delimiter). |
<T> |
public static T |
splitEachLine(CharSequence self, CharSequence regex, Closure<T> closure) Iterates through the given CharSequence line by line, splitting each line using the given regex delimiter. |
<T> |
public static T |
splitEachLine(CharSequence self, Pattern pattern, Closure<T> closure) Iterates through the given CharSequence line by line, splitting each line using the given separator Pattern. |
|
public static boolean |
startsWithAny(CharSequence self, CharSequence prefixes) Tests if this CharSequence starts with any specified prefixes. |
|
public static boolean |
startsWithIgnoreCase(CharSequence self, CharSequence searchString) Checks whether this CharSequence starts with the searchString ignoring the case considerations. |
|
public static String |
stripIndent(CharSequence self) Strips leading spaces from every line in a CharSequence. |
|
public static String |
stripIndent(CharSequence self, boolean forceGroovyBehavior) Same logic as stripIndent(CharSequence) if forceGroovyBehavior is true ,
otherwise Java 13's stripIndent will be invoked. |
|
public static String |
stripIndent(CharSequence self, int numChars) Strips numChars leading characters from every line in a CharSequence.
|
|
public static String |
stripMargin(CharSequence self) Strips leading whitespace/control characters followed by '|' from every line in a CharSequence. |
|
public static String |
stripMargin(CharSequence self, char marginChar) Strips leading whitespace/control characters followed by marginChar from
every line in a CharSequence.
|
|
public static String |
stripMargin(CharSequence self, CharSequence marginChar) Strips leading whitespace/control characters followed by marginChar from
every line in a CharSequence. |
|
public static CharSequence |
take(CharSequence self, int num) Returns the first num elements from this CharSequence.
|
|
public static String |
take(GString self, int num) A GString variant of the equivalent CharSequence method. |
|
public static String |
take(String self, int num) A String variant of the equivalent CharSequence method. |
|
public static CharSequence |
takeAfter(CharSequence self, CharSequence searchString) Returns the CharSequence that exists after the first occurrence of the given
searchString in this CharSequence. |
|
public static String |
takeAfter(String self, CharSequence searchString) A String variant of the equivalent CharSequence method takeAfter(CharSequence,CharSequence). |
|
public static String |
takeAfter(GString self, CharSequence searchString) A GString variant of the equivalent CharSequence method takeAfter(CharSequence,CharSequence). |
|
public static CharSequence |
takeBefore(CharSequence self, CharSequence searchString) Returns the CharSequence that exists before the first occurrence of the given
searchString in this CharSequence. |
|
public static String |
takeBefore(GString self, String searchString) A GString variant of the equivalent CharSequence method takeBefore(CharSequence,CharSequence). |
|
public static String |
takeBefore(String self, String searchString) A String variant of the equivalent CharSequence method takeBefore(CharSequence,CharSequence). |
|
public static CharSequence |
takeBetween(CharSequence self, CharSequence from, CharSequence to) Returns the CharSequence that is in between the first occurrence of the given from and to
CharSequences and empty if the unavailable inputs are given. |
|
public static String |
takeBetween(String self, CharSequence from, CharSequence to) A String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence). |
|
public static String |
takeBetween(GString self, CharSequence from, CharSequence to) A GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence). |
|
public static CharSequence |
takeBetween(CharSequence self, CharSequence enclosure) Takes the characters between the first occurrence of the two subsequent enclosure strings. |
|
public static String |
takeBetween(String self, CharSequence enclosure) A String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence). |
|
public static String |
takeBetween(GString self, CharSequence enclosure) A GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence). |
|
public static CharSequence |
takeBetween(CharSequence self, CharSequence from, CharSequence to, int occurrence) Returns the CharSequence that is in between the given the nth (specified by occurrence) pair of from and to CharSequences and empty if the unavailable inputs are given. |
|
public static String |
takeBetween(String self, CharSequence from, CharSequence to, int occurrence) A String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence,int). |
|
public static String |
takeBetween(GString self, CharSequence from, CharSequence to, int occurrence) A GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence,int). |
|
public static CharSequence |
takeBetween(CharSequence self, CharSequence enclosure, int occurrence) Takes the characters between nth (specified by occurrence) pair of enclosure strings. |
|
public static String |
takeBetween(String self, CharSequence enclosure, int occurrence) A String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,int). |
|
public static String |
takeBetween(GString self, CharSequence enclosure, int occurrence) A GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,int). |
|
public static CharSequence |
takeRight(CharSequence self, int num) Returns the last num elements from this CharSequence. |
|
public static String |
takeRight(String self, int num) A GString variant of the equivalent CharSequence method takeRight(CharSequence,int). |
|
public static String |
takeRight(GString self, int num) A String variant of the equivalent CharSequence method takeRight(CharSequence,int). |
|
public static String |
takeWhile(CharSequence self, Closure condition) Returns the longest prefix of this CharSequence where each element passed to the given closure evaluates to true. |
|
public static String |
takeWhile(GString self, Closure condition) A GString variant of the equivalent GString method. |
|
public static CharSequence |
takeWhile$$bridge(CharSequence self, Closure condition) |
|
public static BigDecimal |
toBigDecimal(CharSequence self) Parses a CharSequence into a BigDecimal |
|
public static BigInteger |
toBigInteger(CharSequence self) Parses a CharSequence into a BigInteger |
|
public static Boolean |
toBoolean(String self) Converts the given string into a Boolean object. |
|
public static Character |
toCharacter(String self) Converts the given string into a Character object using the first character in the string. |
|
public static Double |
toDouble(CharSequence self) Parses a CharSequence into a Double. |
|
public static Float |
toFloat(CharSequence self) Parses a CharSequence into a Float. |
|
public static Integer |
toInteger(CharSequence self) Parses a CharSequence into an Integer. |
|
public static List<String> |
toList(CharSequence self) Converts the given CharSequence into a List of Strings of one character. |
|
public static Long |
toLong(CharSequence self) Parses a CharSequence into a Long |
|
public static Set<String> |
toSet(CharSequence self) Converts the given CharSequence into a Set of unique Strings of one character. |
|
public static Short |
toShort(CharSequence self) Parses a CharSequence into a Short. |
|
public static List<String> |
tokenize(CharSequence self) Tokenizes a CharSequence (with a whitespace as the delimiter). |
|
public static List<String> |
tokenize(CharSequence self, Character delimiter) Tokenizes a CharSequence based on the given character delimiter. |
|
public static List<String> |
tokenize(CharSequence self, CharSequence delimiters) Tokenizes a CharSequence based on the given CharSequence. |
|
public static String |
tr(CharSequence self, CharSequence sourceSet, CharSequence replacementSet) Translates a CharSequence by replacing characters from the sourceSet with characters from replacementSet. |
|
public static String |
uncapitalize(CharSequence self) Convenience method to uncapitalize the first letter of a CharSequence (typically the first letter of a word). |
|
public static String |
unexpand(CharSequence self) Replaces sequences of whitespaces with tabs using tabStops of size 8. |
|
public static String |
unexpand(CharSequence self, int tabStop) Replaces sequences of whitespaces with tabs. |
|
public static String |
unexpandLine(CharSequence self, int tabStop) Replaces sequences of whitespaces with tabs within a line. |
Coerces a CharSequence to a boolean value. A sequence string is coerced to
false
if it is of length 0, and to true
otherwise.
chars
- the character sequenceCoerces a Matcher instance to a boolean value.
matcher
- the matcher Provides a method to perform custom 'dynamic' type conversion
to the given class using the as
operator.
self
- a CharSequencec
- the desired classConverts the GString to a File, or delegates to the default DefaultGroovyMethods.asType.
self
- a GStringc
- the desired class Provides a method to perform custom 'dynamic' type conversion
to the given class using the as
operator.
Example: '123' as Double
By default, the following types are supported:
self
- a Stringc
- the desired classTurns a CharSequence into a regular expression Pattern.
self
- a String to convert into a regular expressionConvenience 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(' ')
self
- The CharSequence to capitalize Pads 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 |
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the result 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.
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+|
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for padding Iterates through this String a character at a time collecting either the
original character or a transformed replacement String. The transform
Closure should return null
to indicate that no transformation is
required for the given character.
assert "Groovy".collectReplacements{ it == 'o' ? '_O_' : null } == 'Gr_O__O_vy' assert "Groovy".collectReplacements{ it.equalsIgnoreCase('O') ? '_O_' : null } == 'Gr_O__O_vy' assert "Groovy".collectReplacements{ char c->
c == 'o' ? '_O_' : null } == 'Gr_O__O_vy' assert "Groovy".collectReplacements{ Character c->
c == 'o' ? '_O_' : null } == 'Gr_O__O_vy' assert "B&W".collectReplacements{it == '&' ? '&' : null
} == 'B&W'
self
- the original Stringtransform
Closure. Iterates through this String a character at a time collecting either the
original character or a transformed replacement String.
The return value is an Optional
either having a value equal to the transformed replacement String
or empty()
to indicate that no transformation is required.
import java.util.function.Function import static java.util.Optional.* Function<Character, Optional<String>> xform1 = s -> s == 'o' ? of('_O') : empty() Function<Character, Optional<String>> xform2 = { it == 'G' ? of('G_') : empty() } assert "Groovy".collectReplacements([xform1, xform2]) == 'G_r_O_Ovy'
self
- the original Stringtransforms
- one or more transforms which potentially convert a single character to a transformed stringtransform
function.Provides an implementation of contains() like Collection.contains to make CharSequences more polymorphic.
self
- a CharSequencetext
- the CharSequence to look for Checks whether this CharSequence contains the searchString
ignoring the caseConsiderations.
self
- the original CharSequencesearchString
- CharSequence being checked against thistrue
if the character sequence represented by the argument exists in this CharSequence
ignoring the case considerations. false
otherwise. Returns false if the argument is nullCounts the number of occurrences of a sub CharSequence.
self
- a CharSequencetext
- a sub CharSequenceReturn a CharSequence with lines (separated by LF, CR/LF, or CR) terminated by the platform specific line separator.
self
- a CharSequence objectDrops 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 ) == ''
self
- the original CharSequencenum
- the number of characters to drop from this Stringnum
ones,
or else an empty String, if this CharSequence has less than num
characters.A GString variant of the equivalent CharSequence method.
self
- the original GStringnum
- the number of characters to drop from this GStringnum
ones,
or else an empty String, if the toString() of this GString has less than num
characters.A String variant of the equivalent CharSequence method.
self
- the original Stringnum
- the number of characters to drop from this Stringnum
ones,
or else an empty String, if the String has less than num
characters. Returns new CharSequence after removing the right num
chars.
Returns empty String if the num
is greater than the length of the CharSequence.
def text = "groovy" assert text.dropRight( 3 ) == 'gro' assert text.dropRight( 6 ) == '' assert text.dropRight( 0 ) == 'groovy' assert text.dropRight( -1 ) == 'groovy' assert text.dropRight( 10 ) == ''
self
- the original CharSequencenum
- number of charactersnum
chars and empty of the num
is greater than the
length of the CharSequenceA String variant of the equivalent CharSequence method dropRight(CharSequence,int).
self
- the original CharSequencenum
- number of charactersnum
chars and empty of the num
is greater than the
length of the CharSequenceA GString variant of the equivalent CharSequence method dropRight(CharSequence,int).
self
- the original CharSequencenum
- number of charactersnum
chars and empty of the num
is greater than the
length of the CharSequenceCreates 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'
self
- the original CharSequencecondition
- the closure that while continuously evaluating to true will cause us to drop elements from
the front of the original CharSequenceA GString variant of the equivalent CharSequence method.
self
- the original GStringcondition
- the closure that while continuously evaluating to true will cause us to drop elements from
the front of the original GStringIterates 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.
self
- a CharSequenceclosure
- 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.
self
- a CharSequencefirstLine
- 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)Processes 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.
self
- the source CharSequenceregex
- a Regex CharSequenceclosure
- a closure with one parameter or as much parameters as groupsProcesses 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.
self
- the source CharSequencepattern
- a regex Patternclosure
- a closure with one parameter or as much parameters as groupsProcesses 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.
self
- the source stringpattern
- a regex Patternclosure
- a closure with one parameter or as much parameters as groupsProcess each regex group matched substring of the given string. 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.
self
- the source stringregex
- a Regex stringclosure
- a closure with one parameter or as much parameters as groupsTests if this CharSequence ends with any specified suffixes.
suffixes
- the suffixes.true
if this CharSequence ends with any specified suffixes Checks whether this CharSequence ends with the searchString
ignoring the case considerations.
self
- the original CharSequencesearchString
- CharSequence bring checked against thistrue
if the character sequence represented by the argument is a suffix of this CharSequence
ignoring the case considerations. false
otherwise. Returns false if the argument is nullExpands all tabs into spaces with tabStops of size 8.
self
- A CharSequence to expandExpands all tabs into spaces. If the CharSequence has multiple lines, expand each line - restarting tab stops at the start of each line.
self
- A CharSequence to expandtabStop
- The number of spaces a tab representsExpands all tabs into spaces. Assumes the CharSequence represents a single line of text.
self
- A line to expandtabStop
- 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 "New York, NY".find(/\d{5}/) == nullIf it does match, we get the matching string back:
assert "New York, NY 10292-0098".find(/\d{5}/) == "10292"If we have capture groups in our expression, we still get back the full match
assert "New York, NY 10292-0098".find(/(\d{5})-?(\d{4})/) == "10292-0098"
self
- a CharSequenceregex
- 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.
self
- a CharSequenceregex
- 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 "New York, NY".find(~/\d{5}/) == nullIf it does match, we get the matching string back:
assert "New York, NY 10292-0098".find(~/\d{5}/) == "10292"If we have capture groups in our expression, the groups are ignored and we get back the full match:
assert "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) == "10292-0098"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
.
self
- a CharSequencepattern
- 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 "New York, NY".find(~/\d{5}/) { match ->
return "-$match-"} == null
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 "New York, NY 10292-0098".find(~/\d{5}/) { match ->
return "-$match-"} == "-10292-"
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 "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
} == "10292"
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 "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { array ->
assert array[0] == "10292-0098"
assert array[1] == "10292"
assert array[2] == "0098"
return array[1]
} == "10292"
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 "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"
} == "2339999"
self
- a CharSequencepattern
- 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 "One Fish, Two Fish, Red Fish, Blue Fish".findAll(/(\w*) Fish/) == expectedIf you need to work with capture groups, then use the closure version of this method or use Groovy's matcher operators or use
eachMatch
.
self
- a CharSequenceregex
- 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 "I could not, would not, with a fox.".findAll(/.ould/) { match ->
"${match}n't"} == ["couldn't", "wouldn'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 orig.findAll(/(.)ocket/) { match, firstLetter->
"$firstLetter>
$match" } == ["W>
Wocket", "P>
Pocket"]
self
- a CharSequenceregex
- 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 "One Fish, Two Fish, Red Fish, Blue Fish".findAll(~/(\w*) Fish/) == expected
self
- a CharSequencepattern
- 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 "I could not, would not, with a fox.".findAll(~/.ould/) { match ->
"${match}n't"} == ["couldn't", "wouldn'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 orig.findAll(~/(.)ocket/) { match, firstLetter->
"$firstLetter>
$match" } == ["W>
Wocket", "P>
Pocket"]
self
- a CharSequencepattern
- the compiled regex Patternclosure
- will be passed the full match plus each of the capturing groups (if any)Selects a List of characters from a CharSequence using a Collection to identify the indices to be selected.
self
- a CharSequenceindices
- a Collection of indicesSupports the range subscript operator for CharSequence or StringBuffer with EmptyRange
self
- a CharSequencerange
- an EmptyRangeSupports the subscript operator for CharSequence.
self
- a CharSequenceindex
- the index of the Character to getSupports the subscript operator for GString.
self
- a GStringindex
- the index of the Character to getSupports the range subscript operator for CharSequence with IntRange.
self
- a CharSequencerange
- an IntRangeSupports the range subscript operator for GString with IntRange.
self
- a GStringrange
- an IntRangeSupports the range subscript operator for CharSequence.
self
- a CharSequencerange
- a RangeSupports the range subscript operator for GString.
self
- a GStringrange
- a RangeSelects a List of values from a Matcher using a Collection to identify the indices to be selected.
self
- a Matcherindices
- a Collection of indices Supports the subscript operator, e.g. matcher[index]
, for a Matcher
.
For an example using no group match,
def p = /ab[d|f]/ def m = "abcabdabeabf" =~ p assert 2 == m.count assert 2 == m.size() // synonym for m.getCount() assert ! m.hasGroup() assert 0 == m.groupCount() def matches = ["abd", "abf"] for (i in 0..<m.count) { assert m[i] == matches[i] }
For an example using group matches,
def p = /(?:ab([c|d|e|f]))/ def m = "abcabdabeabf" =~ p assert 4 == m.count assert m.hasGroup() assert 1 == m.groupCount() def matches = [["abc", "c"], ["abd", "d"], ["abe", "e"], ["abf", "f"]] for (i in 0..<m.count) { assert m[i] == matches[i] }
For another example using group matches,
def m = "abcabdabeabfabxyzabx" =~ /(?:ab([d|x-z]+))/ assert 3 == m.count assert m.hasGroup() assert 1 == m.groupCount() def matches = [["abd", "d"], ["abxyz", "xyz"], ["abx", "x"]] for (i in 0..<m.count) { assert m[i] == matches[i] }
self
- a Matcherindex
- an indexSupports the subscript operator for String.
self
- a Stringindex
- the index of the Character to getSupports the range subscript operator for String with IntRange.
self
- a Stringrange
- an IntRangeSupports the range subscript operator for String.
self
- a Stringrange
- a RangeConverts the given CharSequence into an array of characters.
self
- a CharSequenceFinds the number of Strings matched to the given Matcher.
self
- a MatcherChecks whether a Matcher contains a group or not.
self
- a Matchertrue
if matcher contains at least one group.Returns true if a CharSequence only contains whitespace characters.
self
- The CharSequence to check the characters in Compares a String representing a number to another. A fluent API style alias for compareTo
on BigDecimal
.
left
- a String representing a numberright
- a String representing a numberDetermines if a CharSequence can be parsed as a BigDecimal.
self
- a CharSequenceDetermines if a CharSequence can be parsed as a BigInteger.
self
- a CharSequenceTests if this CharSequence is blank.
true
if this CharSequence is blank'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
.
caseValue
- the case valueswitchValue
- the switch value'Case' implementation for the Pattern class, which allows testing a String against a number of regular expressions.
For example:
switch( str ) { case ~/one/ : // the regex 'one' matches the value of str }Note that this returns true for the case where both the pattern and the 'switch' values are
null
.
caseValue
- the case valueswitchValue
- the switch valueDetermines if a CharSequence can be parsed as a Double.
self
- a CharSequenceDetermines if a CharSequence can be parsed as a Float.
self
- a CharSequenceDetermines if a CharSequence can be parsed as an Integer.
self
- a CharSequenceDetermines if a CharSequence can be parsed as a Long.
self
- a CharSequenceDetermines if a CharSequence can be parsed as a Number.
self
- a CharSequenceReturns an Iterator which traverses each match.
self
- a Matcher objectOverloads the left shift operator to provide an easy way to append multiple objects as string representations to a CharSequence.
self
- a CharSequencevalue
- an ObjectOverloads the left shift operator to provide an easy way to append multiple objects as string representations to a StringBuffer.
self
- a StringBuffervalue
- a value to appendOverloads the left shift operator to provide syntactic sugar for appending to a StringBuilder.
self
- a StringBuildervalue
- an ObjectDetermines if a CharSequence matches the given regular expression.
self
- the CharSequence that is to be matchedpattern
- the regex Pattern to which the string of interest is to be matchedGiven a matcher that matches a string against a pattern, returns true when the string matches the pattern or if a longer string, could match the pattern. For example:
def emailPattern = /\w+@\w+\.\w{2,}/ def matcher = "john@doe" =~ emailPattern assert matcher.matchesPartially() matcher = "john@doe.com" =~ emailPattern assert matcher.matchesPartially() matcher = "john@@" =~ emailPattern assert !matcher.matchesPartially()
self
- the MatcherRemoves a part of a CharSequence by replacing the first occurrence of target within self with empty string and returns the result.
self
- a CharSequencetarget
- an object representing the part to removeRemoves a part of a CharSequence. This replaces the first occurrence of the pattern within self with empty string and returns the result.
self
- a Stringpattern
- a Pattern representing the part to removeRepeats a CharSequence a certain number of times.
self
- a CharSequence to be repeatedfactor
- the number of times the CharSequence should be repeated Overloads 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.
self
- a CharSequenceReturns a String with linefeeds and carriage returns normalized to linefeeds.
self
- a CharSequence object Pads 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
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequence Pads 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
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for padding Pads 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
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting string Pads 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
self
- a CharSequence objectnumberOfChars
- 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.
left
- a CharSequenceright
- any ObjectAppends a String to the string representation of this number.
left
- a Numberright
- a StringAppends the String representation of the given operand to this string.
left
- a Stringright
- any CharSequenceAppends a String to this StringBuffer.
left
- a StringBufferright
- a String Overloads 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.
self
- a CharSequenceSupports the range subscript operator for StringBuffer.
self
- a StringBufferrange
- a Rangevalue
- the object that's toString() will be insertedSupports the range subscript operator for StringBuffer. Index values are treated as characters within the buffer.
self
- a StringBufferrange
- a Rangevalue
- the object that's toString() will be insertedReturns the lines of a CharSequence as a List of String.
self
- a CharSequence objectReplaces all occurrences of replacement CharSequences (supplied via a map) within a provided CharSequence.
assert 'foobar'.replace(f:'b', foo:'bar') == 'boobar' assert 'foobar'.replace(foo:'bar', f:'b') == 'barbar' def replacements = [foo:'bar', f:'b', b: 'f', bar:'boo'] assert 'foobar'.replace(replacements) == 'barfar'
self
- a CharSequencereplacements
- a map of before (key) and after (value) pairs processed in the natural order of the mapReplaces all occurrences of replacement CharSequences (supplied via a map) within a provided CharSequence with control over the internally created StringBuilder's capacity. This method uses a StringBuilder internally. Java auto-expands a StringBuilder's capacity if needed. In rare circumstances, the overhead involved with repeatedly expanding the StringBuilder may become significant. If you have measured the performance of your application and found this to be a significant bottleneck, use this variant to have complete control over the internally created StringBuilder's capacity.
assert 'foobar'.replace(9, [r:'rbaz']) == 'foobarbaz' assert 'foobar'.replace(1, [fooba:'']) == 'r'
self
- a CharSequencecapacity
- an optimization parameter, set to size after replacements or a little larger to avoid resizing overheadsreplacements
- a map of before (key) and after (value) pairs processed in the natural order of the mapReplaces each substring of this CharSequence that matches the given regular expression with the given replacement.
self
- a CharSequenceregex
- the capturing regexreplacement
- the string to be substituted for each matchReplaces all occurrences of a captured group by the result of calling a closure on that text.
Examples:
assert "hello world".replaceAll("(o)") { it[0].toUpperCase() } == "hellO wOrld" assert "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { Object[] itNote 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.->
it[0].toUpperCase() }) == "FOOBAR-FOOBAR-" // 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-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z->
z.toUpperCase() }) == "FOO-FOO-" // 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 group
self
- a CharSequenceregex
- the capturing regexclosure
- 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'
self
- the CharSequence that is to be matchedpattern
- the regex Pattern to which the CharSequence of interest is to be matchedreplacement
- the CharSequence to be substituted for the first matchReplaces all occurrences of a captured group by the result of a closure call on that text.
For examples,
assert "hello world".replaceAll(~"(o)") { it[0].toUpperCase() } == "hellO wOrld" assert "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { it[0].toUpperCase() }) == "FOOBAR-FOOBAR-" // 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-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { Object[] itNote 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.->
it[0].toUpperCase() }) == "FOOBAR-FOOBAR-" // 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-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z->
z.toUpperCase() }) == "FOO-FOO-" // 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 group
self
- a CharSequencepattern
- the capturing regex Patternclosure
- the closure to apply on each captured groupReplaces the first substring of this CharSequence that matches the given regular expression with the given replacement.
self
- a CharSequenceregex
- 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".replaceFirst("(o)") { it[0].toUpperCase() } == "hellO world" // first match assert "hello world".replaceAll("(o)") { it[0].toUpperCase() } == "hellO wOrld" // all matches assert "one fish, two fish".replaceFirst(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } == '1-FISH, two fish' assert "one fish, two fish".replaceAll(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } == '1-FISH, 2-FISH'
self
- a CharSequenceregex
- the capturing regexclosure
- 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'
self
- the CharSequence that is to be matchedpattern
- 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() }
self
- a CharSequencepattern
- the capturing regex Patternclosure
- the closure to apply on the first captured groupCreates a String which is the reverse (backwards) of this CharSequence
self
- a CharSequenceSets the position of the given Matcher to the given index.
self
- a Matcherindex
- the index number Provides the standard Groovy size()
method for CharSequence
.
self
- a CharSequence Provides the standard Groovy size()
method for Matcher
.
self
- a matcher object Provides the standard Groovy size()
method for String
.
self
- a String Provides the standard Groovy size()
method for StringBuffer
.
self
- a StringBufferSplits a CharSequence (with whitespace as delimiter). Similar to tokenize, but returns an Array of String instead of a List.
self
- the CharSequence to splitIterates 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.
self
- a CharSequenceregex
- 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.
self
- a CharSequencepattern
- the regular expression Pattern for the delimiterclosure
- a closureTests if this CharSequence starts with any specified prefixes.
prefixes
- the prefixes.true
if this CharSequence starts with any specified prefixes. Checks whether this CharSequence starts with the searchString
ignoring the case considerations.
self
- the original CharSequencesearchString
- CharSequence being checked against thistrue
if the character sequence represented by the argument is a prefix of this CharSequence
ignoring the case considerations. false
otherwise. Returns false if the argument is nullStrips 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()
self
- a CharSequence to strip the leading spaces fromtoString()
of the CharSequence Same logic as stripIndent(CharSequence) if forceGroovyBehavior
is true
,
otherwise Java 13's stripIndent
will be invoked.
self
- The CharSequence to strip the leading spaces fromforceGroovyBehavior
- force groovy behavior to avoid conflicts with Java13's stripIndent Strips numChars
leading characters from every line in a CharSequence.
assert 'DEF\n456' == '''ABCDEF\n123456'''.stripIndent(3)
self
- The CharSequence to strip the characters fromnumChars
- The number of characters to stripStrips leading whitespace/control characters followed by '|' from every line in a CharSequence.
assert 'ABC\n123\n456' == '''ABC |123 |456'''.stripMargin()
self
- The CharSequence to strip the margin from Strips leading whitespace/control characters followed by marginChar
from
every line in a CharSequence.
assert 'ABC\n123\n456' == '''ABC *123 *456'''.stripMargin('*')
self
- The CharSequence to strip the margin frommarginChar
- Any character that serves as margin delimiter Strips leading whitespace/control characters followed by marginChar
from
every line in a CharSequence.
self
- The CharSequence to strip the margin frommarginChar
- Any character that serves as margin delimiter Returns the first num
elements from this CharSequence.
def text = "Groovy" assert text.take( 0 ) == '' assert text.take( 2 ) == 'Gr' assert text.take( 7 ) == 'Groovy'
self
- the original CharSequencenum
- the number of chars to take from this CharSequencenum
chars,
or else the whole CharSequence if it has less then num
elements.A GString variant of the equivalent CharSequence method.
self
- the original GStringnum
- the number of chars to take from this GStringnum
chars,
or else the whole GString if it has less then num
elements.A String variant of the equivalent CharSequence method.
self
- the original Stringnum
- the number of chars to take from this Stringnum
chars,
or else the whole String if it has less then num
elements. Returns the CharSequence
that exists after the first occurrence of the given
searchString
in this CharSequence.
def text = "Groovy development. Groovy team" assert text.takeAfter( 'Groovy' ) == ' development. Groovy team' assert text.takeAfter( 'team' ) == '' assert text.takeAfter( '' ) == '' assert text.takeAfter( 'Unavailable text' ) == '' assert text.takeAfter( null ) == ''
self
- the original CharSequencesearchString
- CharSequence that is searched in this CharSequenceA String variant of the equivalent CharSequence method takeAfter(CharSequence,CharSequence).
self
- the original CharSequencesearchString
- String that is searched in this CharSequenceA GString variant of the equivalent CharSequence method takeAfter(CharSequence,CharSequence).
self
- the original CharSequencesearchString
- CharSequence that is searched in this CharSequence Returns the CharSequence
that exists before the first occurrence of the given
searchString
in this CharSequence.
def text = "Groovy development. Groovy team" assert text.takeBefore( ' Groovy ' ) == 'Groovy development.' assert text.takeBefore( ' ' ) == 'Groovy' assert text.takeBefore( 'Unavailable text' ) == '' assert text.takeBefore( null ) == ''
self
- the original CharSequencesearchString
- CharSequence that is searched in this CharSequenceA GString variant of the equivalent CharSequence method takeBefore(CharSequence,CharSequence).
self
- the original CharSequencesearchString
- CharSequence that is searched in this CharSequenceA String variant of the equivalent CharSequence method takeBefore(CharSequence,CharSequence).
self
- the original CharSequencesearchString
- CharSequence that is searched in this CharSequence Returns the CharSequence that is in between the first occurrence of the given from
and to
CharSequences and empty if the unavailable inputs are given.
def text = "Groovy" assert text.takeBetween( 'r', 'v' ) == 'oo' assert text.takeBetween( 'r', 'z' ) == '' assert text.takeBetween( 'a', 'r' ) == ''
self
- the original CharSequencefrom
- beginning of searchto
- end of searchA String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence).
self
- the original CharSequencefrom
- beginning of searchto
- end of searchA GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence).
self
- the original CharSequencefrom
- beginning of searchto
- end of search Takes the characters between the first occurrence of the two subsequent enclosure
strings.
def text = "name = 'some name'" assert text.takeBetween( "'" ) == 'some name' assert text.takeBetween( 'z' ) == ''
self
- Original CharSequenceenclosure
- Enclosure CharSequenceenclosure
stringsA String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence).
self
- Original Stringenclosure
- Enclosure CharSequenceenclosure
stringsA GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence).
self
- Original GStringenclosure
- Enclosure CharSequenceenclosure
strings Returns the CharSequence that is in between the given the nth (specified by occurrence) pair of
from
and to
CharSequences and empty if the unavailable inputs are given.
def text = "t1=10 ms, t2=100 ms" assert text.takeBetween( '=', ' ', 0 ) == '10' assert text.takeBetween( '=', ' ', 1 ) == '100' assert text.takeBetween( 't1', 'z' ) == ''
self
- the original CharSequencefrom
- beginning of searchto
- end of searchoccurrence
- nth occurrence that is to be returned. 0 represents first onefrom
and to
CharSequences and empty if the unavailable inputs are given.A String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence,int).
self
- the original Stringfrom
- beginning of searchto
- end of searchoccurrence
- nth occurrence that is to be returned. 0 represents first onefrom
and to
CharSequences and empty if the unavailable inputs are given.A GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,CharSequence,int).
self
- the original GStringfrom
- beginning of searchto
- end of searchoccurrence
- nth occurrence that is to be returned. 0 represents first onefrom
and to
CharSequences and empty if the unavailable inputs are given. Takes the characters between nth (specified by occurrence) pair of enclosure
strings.
def text = "t1='10' ms, t2='100' ms" assert text.takeBetween( "'", 0 ) == '10' assert text.takeBetween( "'", 1 ) == '100' assert text.takeBetween( "'", 2 ) == ''
self
- Original CharSequenceenclosure
- Enclosure CharSequenceoccurrence
- nth occurrence being returnedenclosure
stringsA String variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,int).
self
- Original Stringenclosure
- Enclosure CharSequenceoccurrence
- nth occurrence being returnedenclosure
stringsA GString variant of the equivalent CharSequence method takeBetween(CharSequence,CharSequence,int).
self
- Original GStringenclosure
- Enclosure CharSequenceoccurrence
- nth occurrence being returnedenclosure
strings Returns the last num
elements from this CharSequence.
def text = "Groovy" assert text.takeRight( 0 ) == '' assert text.takeRight( 2 ) == 'vy' assert text.takeRight( 7 ) == 'Groovy'
self
- the original CharSequencenum
- the number of chars to take from this CharSequence from the rightnum
chars,
or else the whole CharSequence if it has less than num
elements.A GString variant of the equivalent CharSequence method takeRight(CharSequence,int).
self
- the original CharSequencenum
- the number of chars to take from this CharSequence from the rightnum
chars,
or else the whole CharSequence if it has less than num
elements.A String variant of the equivalent CharSequence method takeRight(CharSequence,int).
self
- the original GStringnum
- the number of chars to take from this GString from the rightnum
chars,
or else the whole GString if it has less than 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'
self
- the original CharSequencecondition
- the closure that must evaluate to true to continue taking elementsA GString variant of the equivalent GString method.
self
- the original GStringcondition
- the closure that must evaluate to true to continue taking elementsParses a CharSequence into a BigDecimal
self
- a CharSequenceParses a CharSequence into a BigInteger
self
- a CharSequenceConverts the given string into a Boolean object. If the trimmed string is "true", "y" or "1" (ignoring case) then the result is true otherwise it is false.
self
- a StringConverts the given string into a Character object using the first character in the string.
self
- a StringParses a CharSequence into a Double.
self
- a CharSequenceParses a CharSequence into a Float.
self
- a CharSequenceParses a CharSequence into an Integer.
self
- a CharSequenceConverts the given CharSequence into a List of Strings of one character.
self
- a CharSequenceParses a CharSequence into a Long
self
- a CharSequenceConverts the given CharSequence into a Set of unique Strings of one character.
self
- a CharSequenceParses a CharSequence into a Short.
self
- a CharSequenceTokenizes a CharSequence (with a whitespace as the delimiter).
self
- a CharSequenceTokenizes a CharSequence based on the given character delimiter.
For example:
char pathSep = ':' assert "/tmp:/usr".tokenize(pathSep) == ["/tmp", "/usr"]
self
- a CharSequencedelimiter
- the delimiterTokenizes a CharSequence based on the given CharSequence. Each character in the CharSequence is a separate delimiter.
self
- a CharSequencedelimiters
- the delimitersTranslates 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.
self
- the CharSequence that is to be translatedsourceSet
- the set of characters to translate fromreplacementSet
- the set of replacement charactersString
Convenience method to uncapitalize the first letter of a CharSequence (typically the first letter of a word). Example usage:
assert 'H'.uncapitalize() == 'h' assert 'Hello'.uncapitalize() == 'hello' assert 'Hello world'.uncapitalize() == 'hello world' assert 'Hello World'.uncapitalize() == 'hello World' assert 'hello world' == 'Hello World'.split(' ').collect{ it.uncapitalize() }.join(' ')
self
- The CharSequence to uncapitalizeReplaces sequences of whitespaces with tabs using tabStops of size 8.
self
- A CharSequence to unexpandReplaces sequences of whitespaces with tabs.
self
- A CharSequence to unexpandtabStop
- The number of spaces a tab representsReplaces sequences of whitespaces with tabs within a line.
self
- A line to unexpandtabStop
- The number of spaces a tab represents