Class StringUtils
- java.lang.Object
-
- org.drools.util.StringUtils
-
public class StringUtils extends Object
Ripped form commons StringUtil, unless specified:Operations on
Stringthat arenullsafe.- IsEmpty/IsBlank - checks if a String contains text
- Trim/Strip - removes leading and trailing whitespace
- Equals - compares two strings null-safe
- IndexOf/LastIndexOf/Contains - null-safe index-of checks
- IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
- ContainsOnly/ContainsNone - does String contains only/none of these characters
- Substring/Left/Right/Mid - null-safe substring extractions
- SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
- Split/Join - splits a String into an array of substrings and vice versa
- Remove/Delete - removes part of a String
- Replace/Overlay - Searches a String and replaces one String with another
- Chomp/Chop - removes the last part of a String
- LeftPad/RightPad/Center/Repeat - pads a String
- UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
- CountMatches - counts the number of occurrences of one String in another
- IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - checks the characters in a String
- DefaultString - protects against a null input String
- Reverse/ReverseDelimited - reverses a String
- Abbreviate - abbreviates a string using ellipsis
- Difference - compares two Strings and reports on their differences
- LevensteinDistance - the number of changes needed to change one String into another
The
StringUtilsclass defines certain words related to String handling.- null -
null - empty - a zero-length string (
"") - space - the space character (
' ', char 32) - whitespace - the characters defined by
Character.isWhitespace(char) - trim - the characters <= 32 as in
String.trim()
StringUtilshandlesnullinput Strings quietly. That is to say that anullinput will returnnull. Where abooleanorintis being returned details vary by method.A side effect of the
nullhandling is that aNullPointerExceptionshould be considered a bug inStringUtils(except for deprecated methods).Methods in this class give sample code to explain their operation. The symbol
*is used to indicate any input includingnull.- Since:
- 1.0
- Version:
- $Id$
- See Also:
String
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classStringUtils.SIMILARITY_STRATS
-
Field Summary
Fields Modifier and Type Field Description static StringEMPTYThe empty String"".static String[]EMPTY_STRING_ARRAYAn empty immutableStringarray.static intINDEX_NOT_FOUNDRepresents a failed index search.
-
Constructor Summary
Constructors Constructor Description StringUtils()StringUtilsinstances should NOT be constructed in standard programming.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static StringbytesToHex(byte[] bytes)static StringcleanPath(String path)Normalize the path by suppressing sequences like "path/.." and inner simple dots.static booleancodeAwareEqualsIgnoreSpaces(String in1, String in2)Compares two string being equals ignoring whitespaces, but preserving whitespace between double-quotes The two inputs MUST BE valid DRL/Java syntax (this validation is NOT performed by this method, this method assumes they are).static intcodeAwareIndexOf(String str, String searched)static intcodeAwareIndexOf(String str, String searched, int fromIndex)static List<String>codeAwareSplitOnChar(CharSequence string, boolean trimArgs, char... chs)static StringcollectionToDelimitedString(Collection coll, String delim)Convenience method to return a Collection as a delimited (e.g.static StringcollectionToDelimitedString(Collection coll, String delim, String prefix, String suffix)Convenience method to return a Collection as a delimited (e.g.static StringdeleteAny(String inString, String charsToDelete)Delete any character in a given String.static String[]delimitedListToStringArray(String str, String delimiter)Take a String which is a delimited list and convert it to a String array.static String[]delimitedListToStringArray(String str, String delimiter, String charsToDelete)Take a String which is a delimited list and convert it to a String array.static booleanequalsIgnoreSpaces(String s1, String s2)static StringescapeXmlString(String string)static StringextractFirstIdentifier(String string, int start)static intextractFirstIdentifier(String string, StringBuilder builder, int start)static intfindEndOfBlockIndex(CharSequence string, int startOfMethodArgsIndex)static intfindEndOfMethodArgsIndex(CharSequence string, int startOfMethodArgsIndex)static StringgenerateUUID()static StringgetPkgUUID(String gav, String packageName)Retrieve a consistently reproducible package unique identifier.static intindexOfOutOfQuotes(String str, char searched)static intindexOfOutOfQuotes(String str, String searched)static intindexOfOutOfQuotes(String str, String searched, int fromIndex)static booleanisDereferencingIdentifier(String expr)static booleanisEmpty(CharSequence str)Checks if a String is empty ("") or null.static booleanisIdentifier(String expr)static StringlcFirst(String s)static StringlcFirstForBean(String s)static Stringmd5Hash(String s)static Stringpadding(int repeat, char padChar)Returns padding using the specified delimiter repeated to a given length.static StringreadFileAsString(Reader reader)static Stringrepeat(String str, int repeat)Repeat a Stringrepeattimes to form a new String.static Stringreplace(String inString, String oldPattern, String newPattern)Replace all occurences of a substring within a string with another string.static StringreplaceOutOfQuotes(String s, String oldValue, String newValue)static intskipBlanks(String string, int start)static List<String>splitArgumentsList(CharSequence string)static List<String>splitArgumentsList(CharSequence string, boolean trimArgs)static String[]splitPreserveAllTokens(String str, String separatorChars)Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators.static List<String>splitStatements(CharSequence string)static doublestringSimilarity(String s1, String s2, StringUtils.SIMILARITY_STRATS method)static StringtoString(BufferedReader reader)static StringtoString(InputStream is)static StringtoString(Reader reader)static String[]toStringArray(Collection collection)Copy the given Collection into a String array.static URItoURI(String location)static StringucFirst(String s)static voidunescapeJava(Writer out, String str)Unescapes any Java literals found in theStringto aWriter.static StringunescapeJava(String str)Unescapes any Java literals found in theString.static Stringuuid()
-
-
-
Field Detail
-
EMPTY_STRING_ARRAY
public static final String[] EMPTY_STRING_ARRAY
An empty immutableStringarray.
-
EMPTY
public static final String EMPTY
The empty String"".- Since:
- 2.0
- See Also:
- Constant Field Values
-
INDEX_NOT_FOUND
public static final int INDEX_NOT_FOUND
Represents a failed index search.- Since:
- 2.1
- See Also:
- Constant Field Values
-
-
Method Detail
-
isEmpty
public static boolean isEmpty(CharSequence str)
Checks if a String is empty ("") or null.
StringUtils.isEmpty(null) = true StringUtils.isEmpty("") = true StringUtils.isEmpty(" ") = false StringUtils.isEmpty("bob") = false StringUtils.isEmpty(" bob ") = falseNOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank().
- Parameters:
str- the String to check, may be null- Returns:
trueif the String is empty or null
-
repeat
public static String repeat(String str, int repeat)
Repeat a String
repeattimes to form a new String.StringUtils.repeat(null, 2) = null StringUtils.repeat("", 0) = "" StringUtils.repeat("", 2) = "" StringUtils.repeat("a", 3) = "aaa" StringUtils.repeat("ab", 2) = "abab" StringUtils.repeat("a", -2) = ""- Parameters:
str- the String to repeat, may be nullrepeat- number of times to repeat str, negative treated as zero- Returns:
- a new String consisting of the original String repeated,
nullif null String input
-
splitPreserveAllTokens
public static String[] splitPreserveAllTokens(String str, String separatorChars)
Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull. AnullseparatorChars splits on whitespace.StringUtils.splitPreserveAllTokens(null, *) = null StringUtils.splitPreserveAllTokens("", *) = [] StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""] StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""] StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"] StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"] StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"] StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]- Parameters:
str- the String to parse, may benullseparatorChars- the characters used as the delimiters,nullsplits on whitespace- Returns:
- an array of parsed Strings,
nullif null String input - Since:
- 2.1
-
padding
public static String padding(int repeat, char padChar) throws IndexOutOfBoundsException
Returns padding using the specified delimiter repeated to a given length.
StringUtils.padding(0, 'e') = "" StringUtils.padding(3, 'e') = "eee" StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
Note: this method doesn't not support padding with Unicode Supplementary Characters as they require a pair of
chars to be represented. If you are needing to support full I18N of your applications consider usingrepeat(String, int)instead.- Parameters:
repeat- number of times to repeat delimpadChar- character to repeat- Returns:
- String with repeated character
- Throws:
IndexOutOfBoundsException- ifrepeat < 0- See Also:
repeat(String, int)
-
unescapeJava
public static String unescapeJava(String str)
Unescapes any Java literals found in the
String. For example, it will turn a sequence of'\'and'n'into a newline character, unless the'\'is preceded by another'\'.- Parameters:
str- theStringto unescape, may be null- Returns:
- a new unescaped
String,nullif null string input
-
unescapeJava
public static void unescapeJava(Writer out, String str) throws IOException
Unescapes any Java literals found in the
Stringto aWriter.For example, it will turn a sequence of
'\'and'n'into a newline character, unless the'\'is preceded by another'\'.A
nullstring input has no effect.- Parameters:
out- theWriterused to output unescaped charactersstr- theStringto unescape, may be null- Throws:
IllegalArgumentException- if the Writer isnullIOException- if error occurs on underlying Writer
-
cleanPath
public static String cleanPath(String path)
Normalize the path by suppressing sequences like "path/.." and inner simple dots.The result is convenient for path comparison. For other uses, notice that Windows separators ("\") are replaced by simple slashes.
- Parameters:
path- the original path- Returns:
- the normalized path Borrowed from Spring, under the ASL2.0 license.
-
collectionToDelimitedString
public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix)
Convenience method to return a Collection as a delimited (e.g. CSV) String. E.g. useful fortoString()implementations.- Parameters:
coll- the Collection to displaydelim- the delimiter to use (probably a ",")prefix- the String to start each element withsuffix- the String to end each element with- Returns:
- the delimited String Borrowed from Spring, under the ASL2.0 license.
-
collectionToDelimitedString
public static String collectionToDelimitedString(Collection coll, String delim)
Convenience method to return a Collection as a delimited (e.g. CSV) String. E.g. useful fortoString()implementations.- Parameters:
coll- the Collection to displaydelim- the delimiter to use (probably a ",")- Returns:
- the delimited String Borrowed from Spring, under the ASL2.0 license.
-
replace
public static String replace(String inString, String oldPattern, String newPattern)
Replace all occurences of a substring within a string with another string.- Parameters:
inString- String to examineoldPattern- String to replacenewPattern- String to insert- Returns:
- a String with the replacements Borrowed from Spring, under the ASL2.0 license.
-
toURI
public static URI toURI(String location) throws URISyntaxException
- Throws:
URISyntaxException
-
delimitedListToStringArray
public static String[] delimitedListToStringArray(String str, String delimiter)
Take a String which is a delimited list and convert it to a String array.A single delimiter can consists of more than one character: It will still be considered as single delimiter string, rather than as bunch of potential delimiter characters - in contrast to
tokenizeToStringArray.- Parameters:
str- the input Stringdelimiter- the delimiter between elements (this is a single delimiter, rather than a bunch individual delimiter characters)- Returns:
- an array of the tokens in the list Borrowed from Spring, under the ASL2.0 license.
-
delimitedListToStringArray
public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete)
Take a String which is a delimited list and convert it to a String array.A single delimiter can consists of more than one character: It will still be considered as single delimiter string, rather than as bunch of potential delimiter characters - in contrast to
tokenizeToStringArray.- Parameters:
str- the input Stringdelimiter- the delimiter between elements (this is a single delimiter, rather than a bunch individual delimiter characters)charsToDelete- a set of characters to delete. Useful for deleting unwanted line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.- Returns:
- an array of the tokens in the list Borrowed from Spring, under the ASL2.0 license.
-
toStringArray
public static String[] toStringArray(Collection collection)
Copy the given Collection into a String array. The Collection must contain String elements only.- Parameters:
collection- the Collection to copy- Returns:
- the String array (
nullif the passed-in Collection wasnull) Borrowed from Spring, under the ASL2.0 license.
-
deleteAny
public static String deleteAny(String inString, String charsToDelete)
Delete any character in a given String.- Parameters:
inString- the original StringcharsToDelete- a set of characters to delete. E.g. "az\n" will delete 'a's, 'z's and new lines.- Returns:
- the resulting String Borrowed from Spring, under the ASL2.0 license.
-
toString
public static String toString(Reader reader) throws IOException
- Throws:
IOException
-
toString
public static String toString(InputStream is) throws IOException
- Throws:
IOException
-
toString
public static String toString(BufferedReader reader) throws IOException
- Throws:
IOException
-
getPkgUUID
public static String getPkgUUID(String gav, String packageName)
Retrieve a consistently reproducible package unique identifier. It uses both gav and packageName- Parameters:
gav-packageName-- Returns:
-
bytesToHex
public static String bytesToHex(byte[] bytes)
-
generateUUID
public static String generateUUID()
-
extractFirstIdentifier
public static int extractFirstIdentifier(String string, StringBuilder builder, int start)
-
skipBlanks
public static int skipBlanks(String string, int start)
-
splitStatements
public static List<String> splitStatements(CharSequence string)
-
splitArgumentsList
public static List<String> splitArgumentsList(CharSequence string)
-
splitArgumentsList
public static List<String> splitArgumentsList(CharSequence string, boolean trimArgs)
-
codeAwareSplitOnChar
public static List<String> codeAwareSplitOnChar(CharSequence string, boolean trimArgs, char... chs)
-
codeAwareEqualsIgnoreSpaces
public static boolean codeAwareEqualsIgnoreSpaces(String in1, String in2)
Compares two string being equals ignoring whitespaces, but preserving whitespace between double-quotes The two inputs MUST BE valid DRL/Java syntax (this validation is NOT performed by this method, this method assumes they are). Null check: if either of the input is null, this method will return true IFF both are null. Empty check: if either of the input is an empty string, it will be considered as a whitespace during code-aware comparison.
-
findEndOfMethodArgsIndex
public static int findEndOfMethodArgsIndex(CharSequence string, int startOfMethodArgsIndex)
-
findEndOfBlockIndex
public static int findEndOfBlockIndex(CharSequence string, int startOfMethodArgsIndex)
-
indexOfOutOfQuotes
public static int indexOfOutOfQuotes(String str, String searched, int fromIndex)
-
replaceOutOfQuotes
public static String replaceOutOfQuotes(String s, String oldValue, String newValue)
-
indexOfOutOfQuotes
public static int indexOfOutOfQuotes(String str, char searched)
-
isIdentifier
public static boolean isIdentifier(String expr)
-
isDereferencingIdentifier
public static boolean isDereferencingIdentifier(String expr)
-
stringSimilarity
public static double stringSimilarity(String s1, String s2, StringUtils.SIMILARITY_STRATS method)
-
uuid
public static String uuid()
-
-