public final class StringMethods
extends org.apache.commons.lang3.StringUtils
commons-lang3
's StringUtils
class
as one-liners.Constructor and Description |
---|
StringMethods() |
Modifier and Type | Method and Description |
---|---|
static String |
appendPrefix(String prefix,
Character separator,
String body)
Prepends a prefix and a separator to a string, in said order.
|
static String |
appendPrefix(String prefix,
String separator,
String body)
Prepends a prefix and a separator to a string, in said order.
|
static boolean |
containsAny(CharSequence cs,
Collection<? extends CharSequence> searchChars)
Checks whether or not the provided string contains any of the substrings specified in the collection.
|
static boolean |
containsAny(CharSequence cs,
Collection<? extends CharSequence> searchChars,
boolean ignoreCase)
Checks whether or not the provided string contains any of the substrings specified in the collection.
|
static int |
countFinds(Collection<String> strings,
String regularExpression)
Counts the total number of occurrences of the given regular expression in the entries.
|
static int |
countMatches(Collection<String> strings,
String regularExpression)
Counts the number of entries in
strings matching the regular expression regularExpression . |
static String |
decrypt(String encryptedKey)
Decrypt the encrypted password.
|
static String |
ellipsize(String str,
int maxLength)
If the provided string exceeds the provided maximum length, it will be truncated and appended with an ellipsis.
|
static String |
encloseString(String str,
String startEnclosure,
String endEnclosure)
Return a string prepended and appended with the provided strings.
|
static String |
encrypt(String plainKey)
Encrypt the plain text password.
|
static String |
getEnclosedString(String str,
String startEnclosure,
String endEnclosure,
boolean retainEnclosedChar)
Get the substring in between two substrings.
|
static boolean |
hasAMatch(String string,
Collection<String> regularExpressions)
Check if the given string matches any of the given regular expressions.
|
static String |
humanReadableByteCount(long bytes) |
static String |
humanReadableByteCount(long bytes,
boolean si)
Convert provided bytes in words.
|
static String |
implode(Object val,
String separator)
Create a string concatenation of the elements of a string array or
List of objects. |
static boolean |
isEnclosed(String str,
String startEnclosure,
String endEnclosure)
Checks whether or not a string begins and ends with certain substrings.
|
static String |
join(Object[] array,
String separator,
boolean trimElement)
Joins the elements of the provided array into a single string containing the provided array of elements.
|
static String |
join(String[] strArr,
String charSeparator,
com.google.common.base.Function<String,String> entryTransformer)
Joins the elements of the provided array into a single string containing the provided array of elements.
|
static String |
martiniPackageJoin(Collection<MartiniPackage> col,
String separator)
Get the names of the provided packages, and concatenate them into a single string.
|
static String |
removeEnclosingString(String str,
String startEnclosure,
String endEnclosure)
Strip any of a set of characters from the beginning and end of a string.
|
static String[] |
split(String str,
String regex)
Splits this string around matches of the given regular expression
Note: This method was overridden to prevent accidental usage of
StringUtils.split(String, String) over String.split(String) when used
as a one-liner. |
static String |
splitCamelCase(String s)
Use
splitByCharacterTypeCamelCase to split a given string into tokens and
concatenates these tokens via a space. |
static boolean |
startsWithAnyIgnoreCase(CharSequence string,
CharSequence... searchStrings)
Checks if
string starts with any of the items in
searchStrings , regardless of letter case. |
static String |
substitute(Object tokenisedObject)
Substitutes variables within the given source object
with Martini application properties and system property values.
|
static boolean |
substituteAsBoolean(Object tokenisedObject)
Uses
substitute(Object) to substitute variables in the source object,
then checks whether or not the result is equal to true (case insensitive). |
static int |
substituteAsInt(Object tokenisedObject)
Uses
substitute(Object) to substitute variables in the source object,
but attempts to parse the result as an int . |
static int |
substituteAsInt(Object tokenisedObject,
int defaultValue)
Uses
substitute(Object) to substitute variables in the source object,
but attempts to parse the result as an int . |
static String[] |
toArray(Object object)
Get the
String[] representation of the provided object. |
static String[] |
tokenizeToStringArray(String str,
String delimiter,
boolean trimTokens,
boolean ignoreEmptyTokens,
boolean retainDelimiter)
Split the provided string into an array, using the given
delimiter as an indicator of where to split. |
static String[] |
tokenizeToStringArray(String str,
String delimiter,
boolean trimTokens,
boolean ignoreEmptyTokens,
boolean retainDelimiter,
int max)
Split the provided string into an array with a maximum length of
max , using the given delimiter as an indicator of where to split. |
static String[] |
transformEntry(String[] strArr,
com.google.common.base.Function<String,String> entryTransformer)
Transform each element in the array using the provided function, and then return the transformed array.
|
static String |
trimLeadingChar(String str,
String character)
Trim a leading substring.
|
static String |
trimTrailingChar(String str,
String character)
Trim a trailing substring.
|
abbreviate, abbreviate, abbreviateMiddle, appendIfMissing, appendIfMissingIgnoreCase, capitalize, center, center, center, chomp, chomp, chop, compare, compare, compareIgnoreCase, compareIgnoreCase, contains, contains, containsAny, containsAny, containsAny, containsIgnoreCase, containsNone, containsNone, containsOnly, containsOnly, containsWhitespace, countMatches, countMatches, defaultIfBlank, defaultIfEmpty, defaultString, defaultString, deleteWhitespace, difference, endsWith, endsWithAny, endsWithIgnoreCase, equals, equalsAny, equalsAnyIgnoreCase, equalsIgnoreCase, getCommonPrefix, getFuzzyDistance, getJaroWinklerDistance, getLevenshteinDistance, getLevenshteinDistance, indexOf, indexOf, indexOf, indexOf, indexOfAny, indexOfAny, indexOfAny, indexOfAnyBut, indexOfAnyBut, indexOfDifference, indexOfDifference, indexOfIgnoreCase, indexOfIgnoreCase, isAllLowerCase, isAllUpperCase, isAlpha, isAlphanumeric, isAlphanumericSpace, isAlphaSpace, isAnyBlank, isAnyEmpty, isAsciiPrintable, isBlank, isEmpty, isNoneBlank, isNoneEmpty, isNotBlank, isNotEmpty, isNumeric, isNumericSpace, isWhitespace, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, joinWith, lastIndexOf, lastIndexOf, lastIndexOf, lastIndexOf, lastIndexOfAny, lastIndexOfIgnoreCase, lastIndexOfIgnoreCase, lastOrdinalIndexOf, left, leftPad, leftPad, leftPad, length, lowerCase, lowerCase, mid, normalizeSpace, ordinalIndexOf, overlay, prependIfMissing, prependIfMissingIgnoreCase, remove, remove, removeAll, removeEnd, removeEndIgnoreCase, removeFirst, removeIgnoreCase, removePattern, removeStart, removeStartIgnoreCase, repeat, repeat, repeat, replace, replace, replaceAll, replaceChars, replaceChars, replaceEach, replaceEachRepeatedly, replaceFirst, replaceIgnoreCase, replaceIgnoreCase, replaceOnce, replaceOnceIgnoreCase, replacePattern, reverse, reverseDelimited, right, rightPad, rightPad, rightPad, rotate, split, split, split, splitByCharacterType, splitByCharacterTypeCamelCase, splitByWholeSeparator, splitByWholeSeparator, splitByWholeSeparatorPreserveAllTokens, splitByWholeSeparatorPreserveAllTokens, splitPreserveAllTokens, splitPreserveAllTokens, splitPreserveAllTokens, splitPreserveAllTokens, startsWith, startsWithAny, startsWithIgnoreCase, strip, strip, stripAccents, stripAll, stripAll, stripEnd, stripStart, stripToEmpty, stripToNull, substring, substring, substringAfter, substringAfterLast, substringBefore, substringBeforeLast, substringBetween, substringBetween, substringsBetween, swapCase, toEncodedString, toString, trim, trimToEmpty, trimToNull, truncate, truncate, uncapitalize, upperCase, upperCase, wrap, wrap, wrapIfMissing, wrapIfMissing
public static String humanReadableByteCount(long bytes)
public static String humanReadableByteCount(long bytes, boolean si)
bytes
- bytes tosi
- whether or not to use SI unit formatpublic static String splitCamelCase(String s)
Use
splitByCharacterTypeCamelCase
to split a given string into tokens and
concatenates these tokens via a space.
Example usages:
StringMethods.splitCamelCase(null) = null StringMethods.splitCamelCase("") = "" StringMethods.splitCamelCase("ab de fg") = "ab de fg" StringMethods.splitCamelCase("ab de fg") = "ab de fg" StringMethods.splitCamelCase("ab:cd:ef") = "ab: cd: ef" StringMethods.splitCamelCase("number5") = "number 5" StringMethods.splitCamelCase("fooBar") = "foo Bar" StringMethods.splitCamelCase("foo200Bar") = "foo 200 Bar" StringMethods.splitCamelCase("ASFRules") = "ASF Rules"
s
- the string to splitnull
, if the string to split is null
; otherwise, the split stringpublic static String encrypt(String plainKey) throws ToroException
plainKey
- the passwordToroException
- if an error occurspublic static String decrypt(String encryptedKey)
encryptedKey
- the encrypted passwordToroRuntimeException
- if an error occurspublic static String implode(Object val, String separator)
Create a string concatenation of the elements of a string array or List
of objects.
null elements are excluded from the concatenation.
Object.toString()
will be called to get the string representation of each element.
See examples here: StringUtils.join(Object[], String)
.
val
- the array or List
to concatenateseparator
- the character to use in between elements when concatenatingval.toString()
if val
is neither a String[]
nor List
public static String[] tokenizeToStringArray(String str, String delimiter, boolean trimTokens, boolean ignoreEmptyTokens, boolean retainDelimiter)
Split the provided string into an array, using the given
delimiter
as an indicator of where to split.
Example usages:
StringMethods.tokenizeToStringArray(null, ":", false, false, false) = null StringMethods.tokenizeToStringArray("ab:cd:ef", null, false, false, false) = null StringMethods.tokenizeToStringArray(" ab : cd : ef ", ":", true, false, false) = ["ab", "cd", "ef"] StringMethods.tokenizeToStringArray("ab: :cd::ef", ":", false, true, false) = ["ab", " ", "cd", "ef"] StringMethods.tokenizeToStringArray("ab: :cd::ef", ":", false, false, false) = ["ab", " ", "cd", "", "ef"] StringMethods.tokenizeToStringArray("ab:cd:ef", ":", false, false, true) = ["ab", ":", "cd", ":", "ef"]
str
- the string to splitdelimiter
- indicates where to split str
trimTokens
- when set to true, trailing whitespaces are removed from every elementignoreEmptyTokens
- when set to true, empty elements (""
) are removed from the arrayretainDelimiter
- when set to true, delimiter
s in the array will be retained (such that they belong
in their own array index)str
or delimiter
is nullpublic static String[] tokenizeToStringArray(String str, String delimiter, boolean trimTokens, boolean ignoreEmptyTokens, boolean retainDelimiter, int max)
Split the provided string into an array with a maximum length of
max
, using the given delimiter
as an indicator of where to split.
Example usages:
StringMethods.tokenizeToStringArray(null, ":", false, false, false, 0) = null StringMethods.tokenizeToStringArray("ab:cd:ef", null, false, false, false, 0) = null StringMethods.tokenizeToStringArray(" ab : cd : ef ", ":", true, false, false, 0) = ["ab", "cd", "ef"] StringMethods.tokenizeToStringArray("ab: :cd::ef", ":", false, true, false, 0) = ["ab", " ", "cd", "ef"] StringMethods.tokenizeToStringArray("ab: :cd::ef", ":", false, false, false, 0) = ["ab", " ", "cd", "", "ef"] StringMethods.tokenizeToStringArray("ab:cd:ef", ":", false, false, true, 0) = ["ab", ":", "cd", ":", "ef"] StringMethods.tokenizeToStringArray("ab:cd:ef", ":", false, false, false, 2) = ["ab", "cd:ef"]
str
- the string to splitdelimiter
- indicates where to split str
trimTokens
- when set to true, trailing whitespaces are removed from every elementignoreEmptyTokens
- when set to true, empty elements (""
) are removed from the arrayretainDelimiter
- when set to true, delimiter
s in the array will be retained (such that they belong
in their own array index)max
- the maximum number of elements to include in the array; a zero or negative value implies no limitstr
or delimiter
is nullpublic static String removeEnclosingString(String str, String startEnclosure, String endEnclosure)
Strip any of a set of characters from the beginning and end of a string.
Example usages:
StringMethods.removeEnclosingString(null, "*", "/") = null StringMethods.removeEnclosingString("", "*", "/") = "" StringMethods.removeEnclosingString("abc", "", "c") = "ab" StringMethods.removeEnclosingString("abc", "a", "") = "bc" StringMethods.removeEnclosingString("abc", null, null) = "abc" StringMethods.removeEnclosingString(" abc", null, "c") = "ab" StringMethods.removeEnclosingString("abc ", "a", null) = "bc" StringMethods.removeEnclosingString("abc ", null, "") = "abc " StringMethods.removeEnclosingString(" abc", "", null) = " abc" StringMethods.removeEnclosingString(" abc ", null, null) = "abc" StringMethods.removeEnclosingString(" yxabc", "xyz", "cde") = " yxab"
str
- the string to remove characters from, may be nullstartEnclosure
- the characters to remove at the beginning of the string;
a null value means leading whitespace characters will be removedendEnclosure
- the characters to remove at the end of the string
a null value means trailing whitespace characters will be removedstr
is nullpublic static String encloseString(String str, String startEnclosure, String endEnclosure)
Return a string prepended and appended with the provided strings.
Example usages:
StringMethods.encloseString(null, "lettuce", "cheese") = null StringMethods.encloseString("patty", "lettuce", "cheese") = "lettucepattycheese" StringMethods.encloseString("patty", null, "cheese") = "pattycheese" StringMethods.encloseString("patty", "lettuce", null) = "lettucepatty" StringMethods.encloseString("patty", "", null) = "patty" StringMethods.encloseString("patty", null, "") = "patty"
str
- the string to enclosestartEnclosure
- the string to prepend to str
endEnclosure
- the string to append str
public static boolean isEnclosed(String str, String startEnclosure, String endEnclosure)
Checks whether or not a string begins and ends with certain substrings.
Example usages:
StringMethods.isEnclosed(null, "lettuce", "cheese") = false StringMethods.isEnclosed(null, null, null) = true StringMethods.isEnclosed("lettucepattycheese", "lettuce", "cheese") = true StringMethods.isEnclosed(" lettucepattycheese", "lettuce", "cheese") = true StringMethods.isEnclosed("lettucepattycheese ", "lettuce", "cheese") = true StringMethods.isEnclosed("nullpattycheese", null, "cheese") = false StringMethods.isEnclosed("lettucepattynull", "lettuce", null) = false
str
- the string to check; can be nullstartEnclosure
- the substring that str
must begin withendEnclosure
- the substring that str
must end withstr
beings with startEnclosure
and ends with endEnclosure
;
false otherwisepublic static String getEnclosedString(String str, String startEnclosure, String endEnclosure, boolean retainEnclosedChar)
Get the substring in between two substrings.
Example usages:
StringMethods.getEnclosedString(null, "lettuce", "cheese", false) = null StringMethods.getEnclosedString("thelettucepattycheeseend", "tomato", "cheese", false) = null StringMethods.getEnclosedString("thelettucepattycheeseend", "lettuce", "mustard", false) = null StringMethods.getEnclosedString("thelettucepattycheeseend", "lettuce", "cheese", false) = "patty" StringMethods.getEnclosedString("thelettucepattycheeseend", "lettuce", "cheese", true) = "lettucepattycheese"
str
- the string to extract the substring from, may be nullstartEnclosure
- the substring preceding the enclosed stringendEnclosure
- the substring succeeding the enclosed stringretainEnclosedChar
- flag determining whether or not to strip the provided substrings in the returned resultstr
is null;IllegalArgumentException
- when either startEnclosure
or endEnclosure
is nullpublic static String trimTrailingChar(String str, String character)
Trim a trailing substring.
Example usages:
StringMethods.trimTrailingChar(null, "aac") = null StringMethods.trimTrailingChar("aabbccabbaacaacaac", "aac") = aabbccabb StringMethods.trimTrailingChar("aabbccabbaacaacaac", "abc") = aabbccabbaacaacaac StringMethods.trimTrailingChar("aabbccabbaacaacaacccccc", "aac") = aabbccabbaacaacaacccccc StringMethods.trimTrailingChar("aabbccabbaacaacaacccccc", "ac") = aabbccabbaacaacaacccccc StringMethods.trimTrailingChar("aabbccabbaacaacaacccccc", "c") = aabbccabbaacaacaa StringMethods.trimTrailingChar("aabbccabbaacaacaacccccc", null) = aabbccabbaacaacaacccccc StringMethods.trimTrailingChar("aabbccabbaacaanullcaacccccc", null) = aabbccabbaacaanullcaacccccc StringMethods.trimTrailingChar("aabbccabbaacaanullcaaccccccnullnull", null) = aabbccabbaacaanullcaaccccccnullnull StringMethods.trimTrailingChar("aabbccabbaacaanullcaaccccccnullllll", null) = aabbccabbaacaanullcaaccccccnullllll
str
- the string to trimcharacter
- the trailing substring to trimpublic static String trimLeadingChar(String str, String character)
Trim a leading substring.
Example usages:
StringMethods.trimLeadingChar(null, "aac") = null StringMethods.trimLeadingChar("aacaacaacaabbccabb", "aac") = aabbccabb StringMethods.trimLeadingChar("aaccccccaacaacaabbccabb", "aac") = cccccaacaacaabbccabb StringMethods.trimLeadingChar("aaccccccaacaacaabbccabb", "ac") = aaccccccaacaacaabbccabb StringMethods.trimLeadingChar("aaccccccaacaacaabbccabb", "a") = ccccccaacaacaabbccabb StringMethods.trimLeadingChar("aaccccccaacaacaabbccabb", null) = aaccccccaacaacaabbccabb StringMethods.trimLeadingChar("aabbccabbaacaanullcaacccccc", null) = aabbccabbaacaanullcaacccccc StringMethods.trimLeadingChar("nullnullaabbccabbaacaanullcaacccccc", null) = nullnullaabbccabbaacaanullcaacccccc StringMethods.trimLeadingChar("nullllllaabbccabbaacaanullcaacccccc", null) = nullllllaabbccabbaacaanullcaacccccc
str
- the string to trimcharacter
- the leading substring to trimpublic static String ellipsize(String str, int maxLength)
str
- the string to ellipsizemaxLength
- the maximum length of the string before anIllegalArgumentException
- if maxLength
is less than 3public static String martiniPackageJoin(Collection<MartiniPackage> col, String separator)
col
- collection of packagesseparator
- the separator character to usepublic static boolean containsAny(CharSequence cs, Collection<? extends CharSequence> searchChars)
cs
- the string to checksearchChars
- the substrings to look forcs
contains any items from searchChars
;
false otherwisepublic static boolean containsAny(CharSequence cs, Collection<? extends CharSequence> searchChars, boolean ignoreCase)
cs
- the string to checksearchChars
- the substrings to look forignoreCase
- set to false if search is case sensitive; true if notcs
contains any items from searchChars
;
false otherwisepublic static String appendPrefix(String prefix, String separator, String body)
separator
is null, then the four-character string null
is appended after the prefix.prefix
- the prefix to useseparator
- the separator to usebody
- the string to prependprefix + separator + body
public static String appendPrefix(String prefix, Character separator, String body)
separator
is null, then the four-character string null
is appended after the prefix.prefix
- the prefix to useseparator
- the separator to usebody
- the string to prependprefix + separator + body
NullPointerException
- if separator
is nullpublic static String join(Object[] array, String separator, boolean trimElement)
array
- - the array of values to join together, may be nullseparator
- - the separator character to use, null treated as ""trimElement
- whether or not to trim whitespaces around each element's string representationpublic static String join(String[] strArr, String charSeparator, com.google.common.base.Function<String,String> entryTransformer)
strArr
- the array of values to join together, may be nullcharSeparator
- the separator to use when concatenatingentryTransformer
- the function to apply to each element before concatenationpublic static String[] toArray(Object object)
String[]
representation of the provided object.
If the object is a Collection
, then its equivalent String[]
is returned.
If the object is a String
, then an array of its substring separated by , will be returned.
If the object is already a String[]
, then the same array passed in will be returned.
If the object is none of these types, then null is returned.object
- object to convert to arrayString[]
representation of the objectpublic static boolean startsWithAnyIgnoreCase(CharSequence string, CharSequence... searchStrings)
Checks if string
starts with any of the items in
searchStrings
, regardless of letter case.
StringUtils.startsWithAnyIgnoreCase("ABCD", ["AB", "xy"]) = true StringUtils.startsWithAnyIgnoreCase("ABCD", ["ab", "xy"]) = true StringUtils.startsWithAnyIgnoreCase("abcd", ["gh", "xy"]) = false StringUtils.startsWithAnyIgnoreCase("abcd", null) = false StringUtils.startsWithAnyIgnoreCase("", ["abc", ""]) = true StringUtils.startsWithAnyIgnoreCase(null, ["abc", null]) = true StringUtils.startsWithAnyIgnoreCase(null, ["abc", "null"]) = false
string
- the string to checksearchStrings
- the prefixes to look forstring
starts with any of the items in searchStrings
(case insensitive);
false if searchStrings
is null or empty.public static String[] transformEntry(String[] strArr, com.google.common.base.Function<String,String> entryTransformer)
strArr
- the array to transformentryTransformer
- the function that will be used to transform each elementpublic static int countMatches(Collection<String> strings, String regularExpression)
Counts the number of entries in strings
matching the regular expression regularExpression
.
A null collection of entries or regular expression matches none (thus, zero is returned).
strings
- the entries to checkregularExpression
- the regular expression to match againststrings
matching regularExpression
; zero if either strings
or regularExpression
is nullcountFinds(Collection, String)
public static int countFinds(Collection<String> strings, String regularExpression)
Counts the total number of occurrences of the given regular expression in the entries. A null collection of entries or regular expression matches none (thus, zero is returned).
strings
- the entries to checkregularExpression
- the regular expression to findstrings
matching regularExpression
; zero if either strings
or regularExpression
is nullcountMatches(Collection, String)
public static boolean hasAMatch(String string, Collection<String> regularExpressions)
Check if the given string matches any of the given regular expressions.
Results to no matches if either string
or regularExpressions
is null.
public static String substitute(Object tokenisedObject)
Substitutes variables within the given source object with Martini application properties and system property values. This method takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}.
This method allows a default value for unresolved variables. The default value for a variable can be appended to the variable name after the variable default value delimiter. The default value of the "variable default value delimiter" is :-, as in Bash and other *nix shells, as those are arguably where the default ${} delimiter set originated.
The list variable values used are taken from the underlying Martini application properties. Properties in the override file are checked first, then the standard properties file, then the JVM system properties.
The following shows an example with variable default value settings:
String templateString = StringMethods.substitute( "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}." );Resulting in:
The quick brown fox jumped over the lazy dog. 1234567890.
tokenisedObject
- the source objectpublic static int substituteAsInt(Object tokenisedObject) throws NumberFormatException
Uses substitute(Object)
to substitute variables in the source object,
but attempts to parse the result as an int
.
tokenisedObject
- the source objectNumberFormatException
- when the result of the expression can't be parsed as an integerpublic static int substituteAsInt(Object tokenisedObject, int defaultValue)
Uses substitute(Object)
to substitute variables in the source object,
but attempts to parse the result as an int
.
If the result could not be parsed as an integer, the default value is returned.
tokenisedObject
- the source objectdefaultValue
- the value to return if the result could not be parsed as an integerdefaultValue
if the result could not be parsed as an integerpublic static boolean substituteAsBoolean(Object tokenisedObject)
Uses substitute(Object)
to substitute variables in the source object,
then checks whether or not the result is equal to true (case insensitive).
tokenisedObject
- the source objectpublic static String[] split(String str, String regex)
StringUtils.split(String, String)
over String.split(String)
when used
as a one-liner.regex
- the delimiting regular expressionPatternSyntaxException
- if the regular expression's syntax is invalidCopyright © 2021. All rights reserved.