Class StringUtil
- java.lang.Object
-
- com.intellij.openapi.util.text.StringUtil
-
- jetbrains.buildServer.util.StringUtil
-
public class StringUtil extends StringUtil
- Author:
- Kir
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceStringUtil.EscapeInfoProviderDeprecated.static interfaceStringUtil.EscapeInfoProvider2String escaping info provider.static interfaceStringUtil.LineProcessor
-
Field Summary
Fields Modifier and Type Field Description static StringB_POSTFIXstatic char[]DEFAULT_SEPARATORSstatic StringEMPTYstatic StringENABLE_LEGACY_URL_ENCODING_PROPERTYstatic longGBstatic StringGB_POSTFIXstatic longKBstatic StringKB_POSTFIXstatic longMBstatic StringMB_POSTFIXstatic StringNAstatic Filter<String>NOT_EMPTY_STRING_FILTERstatic StringUtil.EscapeInfoProviderSTD_ESCAPERDeprecated.useSTD_ESCAPER2static StringUtil.EscapeInfoProvider2STD_ESCAPER2static longTBstatic StringTB_POSTFIX-
Fields inherited from class com.intellij.openapi.util.text.StringUtil
TRIMMER
-
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static booleanareEqual(String string1, String string2)Checks whether two given strings are equal.static booleanareEqualIgnoringCase(String string1, String string2)Checks whether two given strings are equal, ignoring characters case.static StringbiteOffPostfix(String line, String postfix)static charcharAt(String string, int position)Returns the n-th character of the string.static StringcollapseSpaces(String str)Replaces a sequence of space characters with single whitespace.static intcompare(String s1, String s2)static StringconvertAndCollapseSlashes(String s)Replaces backslashes with forward and collapse consequent slashes into one.static StringconvertCamelToCharSeparated(String camelCasedString, char serapator)static StringconvertCamelToDashSeparated(String camelCasedString)static StringconvertCamelToSpaceSeparated(String camelCasedString)static voidconvertStringsToLowerCase(List<String> strings)Converts all strings inside the given list to lower case.static StringconvertWildcardToRegexp(String pattern)Converts pattern with wildcards (* or ?) to regular expression.static Iterator<String>createEscapedTokenizer(String string, char del)Split string into tokens, ignores delimiters with escaping ('\')static StringdateToString(Date date)static StringdecodeURL(String source)static StringdecodeURL(String source, String encoding)Copied from org.springframework.web.util.UriUtils#decode Copied to not include whole spring package to modules where only UriUtils#decodeURL is neededstatic booleandifferCaseOnly(String string1, String string2)Checks that the two given strings are different but differ in their case only.static StringdoubleQuote(String string)Quotes the string with double quotes.static StringelapsedTimeToString(long millis)static StringelapsedTimeToString(Date date)static StringemptyIfNull(String string)Returns given string if it is not null, or empty string if a null given.static StringencodeURLParameter(String source)Encode the given URL query parameter with the given encoding.static StringencodeURLParameter(String source, String encoding)Encode the given URL query parameter with the given encoding.static voidescapeDataForCSV(Writer writer, String... data)static StringescapeForCSV(String s)Escapes the value to be used in a CSV row.static StringescapeForCSV(String... data)static StringescapeForRegex(String str)Converts string to a form which is safe to use for regular expressions.static StringescapeHTML(String text, boolean replaceQuotes)static StringescapeQuotesIfWindows(String value)static StringescapeStr(String str, StringUtil.EscapeInfoProvider p)static StringescapeStr(String str, StringUtil.EscapeInfoProvider2 p)Escapes characters specified by provider with '\' and specified character.static intfindInvalidXMLChar(String value)Deprecated.Please usefindInvalidXMLCodePoint(String)instead.static intfindInvalidXMLCodePoint(String value)Looks for Unicode code points that cannot be presented in XML.static StringformatFileSize(long fileSize)static StringformatFileSize(long fileSize, int maxFractionDigits)static StringformatFileSize(File file)static StringformatInt(int value)static StringformatInt(int value, int length)static StringformatInt(int value, int length, char fillChar)static StringformatPercent(float numerator, long denominator)static StringformatTextForWeb(String txt)Formats text for showing on the web page preserving original text formatting.static StringgenerateUniqueHash()NOTE: This could take more than 30 seconds for the first call Generates unique hash value.static StringgenerateUniqueHashQuickly()Quickly returns non-secure random hash valuestatic StringgetOrdinal(int number)Return ordinal ending for a number, i.e.static booleanhasNonBMPCharacters(String str)static booleanhasParameterReferences(String str)Returns true if string contains parameter references of form %param.name% This method is equals toReferencesResolverUtil.containsReference(java.lang.String, java.lang.String[], boolean)with args (str, new String[0], true), except str nullability.static intindexOf(String currentString, char findWhat, StringUtil.EscapeInfoProvider escaper)static intindexOf(String currentString, char findWhat, StringUtil.EscapeInfoProvider2 escaper)static booleanisAPositiveNumber(String value)static booleanisNumber(String value)static booleanisTrue(String property)static booleanisUpperCase(String str)Check whether the string is uppercase: contains at least one uppercase letter and no lowercase letters.static booleanisValidXMLChar(char c)Deprecated.Please useisValidXMLCodePoint(int)instead.
Section 2.2 of the XML spec describes which Unicode code points are valid in XML:static booleanisValidXMLCodePoint(int c)Section 2.2 of the XML spec describes which Unicode code points are valid in XML:static Stringjoin(String separator, Iterable toJoin)Simple string joiner with given separator.static voidjoin(String separator, Iterable toJoin, StringBuilder result)Simple string joiner with given separator.static Stringjoin(String separator, Object... toJoin)Simple string joiner with given separator.static StringlastPartOf(String s, char separator)static StringmillisToString(long timeIntervalMs, boolean useMillis)static StringnewLineToSpaceDelimited(String str)static StringnotEmpty(String string, String defaultValue)Returns either given string, or if it is null or empty, thedefaultValue.static StringnullIfEmpty(String string)Returns given string if it is not empty, or null if it is empty.static StringobjectToString(Object object)Safely callsObject.toString().static longparseFileSize(String fileSizeStr)Parses file size from string.static StringpeekNthDelimitedField(String string, char separator, int nth, boolean trim)Treats the given string as a separator delimited string, and returns the nth field from this string.static voidprocessLines(File file, StringUtil.LineProcessor processor)static voidprocessLines(InputStream in, StringUtil.LineProcessor processor)static voidprocessLines(String str, StringUtil.LineProcessor processor)static StringpropertiesToString(Map<String,String> props, StringUtil.EscapeInfoProvider escaper)static StringpropertiesToString(Map<String,String> props, StringUtil.EscapeInfoProvider2 escaper)static StringremoveLeadingAndTailingSlash(String path)Combines #removeLeadingSlash and #removeTailingSlashstatic StringremoveLeadingSlash(String path)If given string starts with /, remove it and return remaining stringstatic StringremoveNonBMPCharacters(String str)Replaces all non-BMP characters with the sign character.static StringremoveSuffix(String string, String suffix, boolean caseSensitive)If the given string ends with the specified suffix, removes it.static StringremoveTailingSlash(String path)If given string ends with /, remove it and return remaining stringstatic Stringrepeat(String whatRepeat, String separator, int times)static voidrepeat(String whatRepeat, String separator, int times, StringBuilder builder)static voidreplace(StringBuilder buf, String what, String with)Replaces all occurrences of the what substring with the with in the specified string buffer.static voidreplace(StringBuilder buf, Pattern pattern, String with)Replaces all occurrences of the pattern with the with string in the specified string buffer.static StringreplaceInvalidXmlChars(String str)Replaces all unicode code points illegal in xml with spacesstatic StringreplaceNewLines(String str, String replacement)static StringreplaceNonAlphaNumericChars(String originalStr, char toReplace)Replaces all characters except A-Za-z0-9_ to specified character.static PatternsearchByKeywordPattern(String keyword, boolean caseInsensitive)Returns RegEx pattern to search by specified keyword.static List<String>split(String values)Splits values using default separators, note that empty strings are then removed from the result.static List<String>split(String values, boolean removeEmpty, char... separators)Splits values using specified separators, empty strings are preserved.static List<String>splitCommandArgumentsAndUnquote(String line)This utility differs from splitHonorQuote: it considers quote in sequence 'ddd\" -' as boundary quote.static List<String>splitHonorQuotes(String s)static List<String>splitHonorQuotes(String s, char separator)static String[]splitLines(String string)Splits the string by lines.static StringstackTrace(Throwable exception)static Map<String,String>stringToProperties(String string, StringUtil.EscapeInfoProvider escaper)static Map<String,String>stringToProperties(String string, StringUtil.EscapeInfoProvider2 escaper)performs conversion of string to property map with string name checking.static Map<String,String>stringToProperties(String string, StringUtil.EscapeInfoProvider2 escaper, boolean strictNameCheck)Converts string to property mapstatic Map<String,String>stringToProperties(String string, StringUtil.EscapeInfoProvider escaper, boolean strictNameCheck)static StringstringValueOf(Object obj, String defaultValue)static StringstripLeftAndRight(String s, CharFilter filter)Returns the stringsstripped from the beginning and end with symbols matched byfilter.static StringsubstringByRegex(CharSequence text, Pattern pattern, int groupNr)Gets the inner part of string that specified with the regular expression.static Stringtrim(String s)Returns the trimmed string, ornullstatic StringtrimAndNull(String string)Trims the given string and returns it if after trimming if is not empty; otherwise returns null.static StringtrimRight(String string)Removes the right (end) spaces from the string.static voidtrimStringBuilderLeft(StringBuilder buf)Removes starting spaces.static StringtruncateStringValue(String str, int maxLength)Truncates string, returns part of the initial string with length up to max length characters.static StringtruncateStringValueWithDotsAtCenter(String str, int maxLength)Truncates string and adds dots to the center of the string if it was truncated.static StringtruncateStringValueWithDotsAtEnd(String str, int maxLength)Truncates string and adds dots to the end of the string if it was truncated.static StringunescapeStr(String str, StringUtil.EscapeInfoProvider p)static StringunescapeStr(String str, StringUtil.EscapeInfoProvider2 p)Unescapes characters specified by provider with '\' and specified character.static StringwithPlural(long n, String base)Returns duly pluralized form of "N items" text-
Methods inherited from class com.intellij.openapi.util.text.StringUtil
capitalize, capitalizeWithJavaBeanConvention, capitalizeWords, capitalizeWords, capitalsOnly, charsEqualIgnoreCase, commonPrefix, commonPrefixLength, commonSuffix, commonSuffixLength, compareVersionNumbers, containsAlphaCharacters, containsAnyChar, containsIgnoreCase, convertLineSeparators, convertLineSeparators, convertLineSeparators, countChars, countNewLines, decapitalize, difference, endsWith, endsWithChar, endsWithIgnoreCase, escapeProperty, escapeQuotes, escapeStringCharacters, escapeStringCharacters, escapeStringCharacters, escapeToRegexp, escapeXml, filterEmptyStrings, findFirst, first, first, firstLetterToUpperCase, fixVariableNameDerivedFromPropertyName, getLineBreakCount, getMessage, getOccurenceCount, getPackageName, getPackageName, getPropertyName, getQualifiedName, getShortName, getShortName, getShortName, getThrowableText, getThrowableText, getWordsIn, indexOf, indexOf, indexOfIgnoreCase, isEmpty, isEmptyOrSpaces, isJavaIdentifier, isJavaIdentifierPart, isJavaIdentifierStart, isNotEmpty, isPreposition, isPreposition, isQuotedString, isVowel, join, join, join, join, join, join, join, joinOrNull, last, lineColToOffset, notNullize, notNullize, offsetToLineNumber, parseInt, parseLong, pluralize, pluralize, quoteReplacement, repeatSymbol, repeatSymbol, replace, replace, replace, replaceChar, replaceIgnoreCase, replaceSubstring, shiftIndentInside, split, splitByLines, startsWith, startsWithChar, startsWithConcatenationOf, startsWithIgnoreCase, stringHashCode, stringHashCode, stringHashCode, stringHashCodeInsensitive, stringHashCodeInsensitive, stringHashCodeInsensitive, strip, stripQuotesAroundValue, surround, tail, tokenize, toLowerCase, toLowerCase, toTitleCase, toUpperCase, trimEnd, trimStart, unescapeStringCharacters, unescapeXml, unpluralize, unquoteString, wordsToBeginFromUpperCase, zip
-
-
-
-
Field Detail
-
DEFAULT_SEPARATORS
public static final char[] DEFAULT_SEPARATORS
-
EMPTY
public static final String EMPTY
- See Also:
- Constant Field Values
-
NA
@NonNls public static final String NA
- See Also:
- Constant Field Values
-
KB
public static final long KB
- See Also:
- Constant Field Values
-
MB
public static final long MB
- See Also:
- Constant Field Values
-
GB
public static final long GB
- See Also:
- Constant Field Values
-
TB
public static final long TB
- See Also:
- Constant Field Values
-
B_POSTFIX
public static final String B_POSTFIX
- See Also:
- Constant Field Values
-
KB_POSTFIX
public static final String KB_POSTFIX
- See Also:
- Constant Field Values
-
MB_POSTFIX
public static final String MB_POSTFIX
- See Also:
- Constant Field Values
-
GB_POSTFIX
public static final String GB_POSTFIX
- See Also:
- Constant Field Values
-
TB_POSTFIX
public static final String TB_POSTFIX
- See Also:
- Constant Field Values
-
ENABLE_LEGACY_URL_ENCODING_PROPERTY
public static final String ENABLE_LEGACY_URL_ENCODING_PROPERTY
- See Also:
- Constant Field Values
-
STD_ESCAPER
@Deprecated public static final StringUtil.EscapeInfoProvider STD_ESCAPER
Deprecated.useSTD_ESCAPER2
-
STD_ESCAPER2
public static final StringUtil.EscapeInfoProvider2 STD_ESCAPER2
-
-
Method Detail
-
areEqual
@Contract("null, null -> true") public static boolean areEqual(@Nullable String string1, @Nullable String string2)Checks whether two given strings are equal. Both strings may be null. An empty string and null treated as different strings.- Parameters:
string1- the first string to compare.string2- the second string to compare.- Returns:
- strings are equal.
- Since:
- 5.0
-
areEqualIgnoringCase
@Contract("null, null -> true") public static boolean areEqualIgnoringCase(@Nullable String string1, @Nullable String string2)Checks whether two given strings are equal, ignoring characters case. Both strings may be null. An empty string and null treated as different strings.- Parameters:
string1- the first string to compare.string2- the second string to compare.- Returns:
- strings are equal.
- Since:
- 5.0
-
differCaseOnly
public static boolean differCaseOnly(@NotNull String string1, @NotNull String string2)Checks that the two given strings are different but differ in their case only.- Parameters:
string1- the first string to compare.string2- the second string to compare.- Returns:
- differ but in case only.
- Since:
- 8.0
-
isUpperCase
public static boolean isUpperCase(@NotNull String str)Check whether the string is uppercase: contains at least one uppercase letter and no lowercase letters. Non-letter symbols are ignored.- Parameters:
str- the string to check.- Returns:
- is uppercase.
- Since:
- 8.0
-
splitCommandArgumentsAndUnquote
@NotNull public static List<String> splitCommandArgumentsAndUnquote(@NotNull String line)
This utility differs from splitHonorQuote: it considers quote in sequence 'ddd\" -' as boundary quote. So it can split "-Dffoo=c:\some\path\ddd\" -Dfff=sss correctly.
-
biteOffPostfix
@NotNull public static String biteOffPostfix(@NotNull String line, @NotNull String postfix)
-
truncateStringValue
@Nullable @Contract("null, _ -> null; !null, _ -> !null") public static String truncateStringValue(@Nullable String str, int maxLength)Truncates string, returns part of the initial string with length up to max length characters.- Parameters:
str- string to truncatemaxLength- max length- Returns:
- see above
-
truncateStringValueWithDotsAtEnd
@Nullable @Contract("null, _ -> null; !null, _ -> !null") public static String truncateStringValueWithDotsAtEnd(@Nullable String str, int maxLength)Truncates string and adds dots to the end of the string if it was truncated.- Parameters:
str- string to truncatemaxLength- max length of the resulting string- Returns:
- truncated string with dots at the end
-
truncateStringValueWithDotsAtCenter
@Nullable @Contract("null, _ -> null; !null, _ -> !null") public static String truncateStringValueWithDotsAtCenter(@Nullable String str, int maxLength)Truncates string and adds dots to the center of the string if it was truncated.- Parameters:
str- string to truncatemaxLength- max length of the resulting string- Returns:
- truncated string with dots at the center
-
isValidXMLCodePoint
public static boolean isValidXMLCodePoint(int c)
Section 2.2 of the XML spec describes which Unicode code points are valid in XML:
Code points outside this set cannot be represented in XML.#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]- Parameters:
c- The code point to inspect.- Returns:
- Whether the specified character is valid in XML.
- Since:
- 2021.2
-
isValidXMLChar
@Deprecated public static boolean isValidXMLChar(char c)
Deprecated.Please useisValidXMLCodePoint(int)instead.
Section 2.2 of the XML spec describes which Unicode code points are valid in XML:
Code points outside this set cannot be represented in XML.#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]- Parameters:
c- The character to inspect.- Returns:
- Whether the specified character is valid in XML.
-
findInvalidXMLCodePoint
public static int findInvalidXMLCodePoint(@NotNull String value)Looks for Unicode code points that cannot be presented in XML. To ensure that given string does not contain illegal code points please usereplaceInvalidXmlChars(String).
Example:
String test = "ab?ba";
int invalidPos = findInvalidXMLCodePoint(test); // 3
int invalidCodePoint = test.codePointAt(invalidPos); // 0xD800
String validString = test.substring(0, invalidPos) + test.substring(invalidPos + Character.charCount(invalidCodePoint)); //abba- Parameters:
value- value- Returns:
- index of the first char of the invalid XML code point in the string or -1 if all code points are valid.
- Since:
- 2021.2
-
findInvalidXMLChar
@Deprecated public static int findInvalidXMLChar(@NotNull String value)
Deprecated.Please usefindInvalidXMLCodePoint(String)instead. Looks for characters that cannot be presented in XML To ensure that given string does not contain illegal characters please usereplaceInvalidXmlChars(String).- Parameters:
value- value- Returns:
- index of invalid XML character in the string or -1 if all chars are valid
-
replaceInvalidXmlChars
@NotNull public static String replaceInvalidXmlChars(@NotNull String str)
Replaces all unicode code points illegal in xml with spaces- Parameters:
str- string to replace- Returns:
- string with replaced unicode code points
- Since:
- 6.5
-
generateUniqueHash
@NotNull public static String generateUniqueHash()
NOTE: This could take more than 30 seconds for the first call Generates unique hash value. Can be used for generating various identifiers like session id.- Returns:
- hash value
-
generateUniqueHashQuickly
@NotNull public static String generateUniqueHashQuickly()
Quickly returns non-secure random hash value- Returns:
- see above
- Since:
- 8.1
-
searchByKeywordPattern
@NotNull public static Pattern searchByKeywordPattern(@NotNull String keyword, boolean caseInsensitive)
Returns RegEx pattern to search by specified keyword.- Parameters:
keyword- keywordcaseInsensitive- is case sensitive- Returns:
- pattern to match it
-
escapeForRegex
@NotNull public static String escapeForRegex(@NotNull String str)
Converts string to a form which is safe to use for regular expressions.- Parameters:
str- string to escape- Returns:
- see above
-
convertWildcardToRegexp
@NotNull public static String convertWildcardToRegexp(@NotNull String pattern)
Converts pattern with wildcards (* or ?) to regular expression.- Parameters:
pattern- pattern- Returns:
- regexp
-
split
@NotNull public static List<String> split(@NotNull String values)
Splits values using default separators, note that empty strings are then removed from the result.- Parameters:
values- value to split- Returns:
- list of splitted values with empty strings removed
-
split
@NotNull public static List<String> split(@NotNull String values, boolean removeEmpty, @NotNull char... separators)
Splits values using specified separators, empty strings are preserved. If input string ends with one of separators, empty string after it is not included into result- Parameters:
values- values to splitremoveEmpty- if true then empty strings will not be returnedseparators- separators- Returns:
- list of splitted values (with empty strings possible)
-
isAPositiveNumber
@Contract("null -> false") public static boolean isAPositiveNumber(@Nullable String value)
-
isNumber
@Contract("null -> false") public static boolean isNumber(@Nullable String value)
-
getOrdinal
@NotNull public static String getOrdinal(int number)
Return ordinal ending for a number, i.e. st for 1, nd for 2 and rd for 33.- Parameters:
number- number, whose ordinal ending should be returned- Returns:
- see above
-
join
@NotNull public static String join(@Nullable String separator, @NotNull Iterable toJoin)
Simple string joiner with given separator. Null values are ignored- Parameters:
separator- separator for joined stringtoJoin- object to join, if an object is null, it is ignored- Returns:
- joined string
- Since:
- 5.0
-
join
public static void join(@Nullable String separator, @NotNull Iterable toJoin, @NotNull StringBuilder result)Simple string joiner with given separator. Null values are ignored- Parameters:
separator- separator for joined stringtoJoin- object to join, if an object is null, it is ignoredresult- string builder to put result to- Since:
- 5.0
-
join
@NotNull public static String join(@Nullable String separator, @NotNull Object... toJoin)
Simple string joiner with given separator. Null values are ignored- Parameters:
separator- separator for joined stringtoJoin- object to join, if an object is null, it is ignored- Returns:
- joined string
- Since:
- 5.0
-
doubleQuote
@NotNull public static String doubleQuote(@NotNull String string)
Quotes the string with double quotes.- Parameters:
string- string to quote- Returns:
- original string quoted with double quotes
- Since:
- 8.0
-
createEscapedTokenizer
public static Iterator<String> createEscapedTokenizer(String string, char del)
Split string into tokens, ignores delimiters with escaping ('\')- Parameters:
string- string data to tokenizedel- selimiter- Returns:
- result iterator
-
indexOf
@Deprecated public static int indexOf(String currentString, char findWhat, StringUtil.EscapeInfoProvider escaper)
-
indexOf
public static int indexOf(String currentString, char findWhat, StringUtil.EscapeInfoProvider2 escaper)
-
stringToProperties
@Deprecated @NotNull public static Map<String,String> stringToProperties(@NotNull String string, @NotNull StringUtil.EscapeInfoProvider escaper) throws ParseException
Deprecated.performs conversion of string to property map with string name checking.- Parameters:
string- source stringescaper- escaping rule provider- Returns:
- the resulted property map
- Throws:
ParseException- if parsing of the property sting failed- See Also:
stringToProperties(String, jetbrains.buildServer.util.StringUtil.EscapeInfoProvider, boolean)
-
stringToProperties
@NotNull public static Map<String,String> stringToProperties(@NotNull String string, @NotNull StringUtil.EscapeInfoProvider2 escaper) throws ParseException
performs conversion of string to property map with string name checking.- Parameters:
string- source stringescaper- escaping rule provider- Returns:
- the resulted property map
- Throws:
ParseException- if parsing of the property sting failed- See Also:
stringToProperties(String, jetbrains.buildServer.util.StringUtil.EscapeInfoProvider2, boolean)
-
stringToProperties
@Deprecated @NotNull public static Map<String,String> stringToProperties(@NotNull String string, @NotNull StringUtil.EscapeInfoProvider escaper, boolean strictNameCheck) throws ParseException
Deprecated.Converts string to property map- Parameters:
string- in a form of "name1='value' name2='value' ..."escaper- escaping rule providerstrictNameCheck- if true each name is checked to be a valid java identifier, otherwise it's only checked for absence of spaces- Returns:
- the resulted property map
- Throws:
ParseException- if parsing of the property sting failed
-
stringToProperties
@NotNull public static Map<String,String> stringToProperties(@NotNull String string, @NotNull StringUtil.EscapeInfoProvider2 escaper, boolean strictNameCheck) throws ParseException
Converts string to property map- Parameters:
string- in a form of "name1='value' name2='value' ..."escaper- escaping rule providerstrictNameCheck- if true each name is checked to be a valid java identifier, otherwise it's only checked for absence of spaces- Returns:
- the resulted property map
- Throws:
ParseException- if parsing of the property sting failed
-
propertiesToString
@Deprecated public static String propertiesToString(Map<String,String> props, StringUtil.EscapeInfoProvider escaper)
-
propertiesToString
public static String propertiesToString(Map<String,String> props, StringUtil.EscapeInfoProvider2 escaper)
-
repeat
public static void repeat(String whatRepeat, String separator, int times, StringBuilder builder)
-
isTrue
@Contract("null -> false") public static boolean isTrue(@Nullable String property)
-
convertStringsToLowerCase
public static void convertStringsToLowerCase(@NotNull List<String> strings)Converts all strings inside the given list to lower case.- Parameters:
strings- list of strings.- Since:
- 5.0
-
removeTailingSlash
@Nullable @Contract("null->null;!null->!null") public static String removeTailingSlash(@Nullable String path)If given string ends with /, remove it and return remaining string- Parameters:
path- input string- Returns:
- see above
- Since:
- 5.0
-
removeSuffix
public static String removeSuffix(@NotNull String string, @NotNull String suffix, boolean caseSensitive)
If the given string ends with the specified suffix, removes it.- Parameters:
string- string to check.suffix- suffix to remove from the string.caseSensitive- whether the suffix is case sensitive.- Returns:
- the string without the suffix.
- Since:
- 9.0
-
removeLeadingSlash
@Nullable @Contract("null->null;!null->!null") public static String removeLeadingSlash(@Nullable String path)If given string starts with /, remove it and return remaining string- Parameters:
path- input string- Returns:
- see above
- Since:
- 5.0
-
removeLeadingAndTailingSlash
@Nullable @Contract("null->null;!null->!null") public static String removeLeadingAndTailingSlash(@Nullable String path)Combines #removeLeadingSlash and #removeTailingSlash- Parameters:
path- input string- Returns:
- see above
- Since:
- 8.0
-
replace
public static void replace(@NotNull StringBuilder buf, @NotNull String what, @NotNull String with)Replaces all occurrences of the what substring with the with in the specified string buffer.- Parameters:
buf- string buffer where perform replacing.what- substring to find and change.with- substring that will be replaced with.
-
replace
public static void replace(@NotNull StringBuilder buf, @NotNull Pattern pattern, @NotNull String with)Replaces all occurrences of the pattern with the with string in the specified string buffer.- Parameters:
buf- string buffer where perform replacing.pattern- pattern to find.with- substring that will be replaced with.
-
convertAndCollapseSlashes
@NotNull public static String convertAndCollapseSlashes(@NotNull String s)
Replaces backslashes with forward and collapse consequent slashes into one. Same as s.replaceAll("\\\\", "/").replaceAll("/{2,}", "/") but faster.- Parameters:
s- input string- Returns:
- see above
-
processLines
public static void processLines(@NotNull String str, @NotNull StringUtil.LineProcessor processor) throws IOException- Throws:
IOException
-
formatPercent
@NotNull public static String formatPercent(float numerator, long denominator)
-
formatFileSize
@NotNull public static String formatFileSize(File file)
- Returns:
- file size as a human friendly string.
- Since:
- 9.0
-
formatFileSize
@NotNull public static String formatFileSize(long fileSize)
- Parameters:
fileSize- in bytes- Returns:
- file size as a human friendly string.
-
formatFileSize
@NotNull public static String formatFileSize(long fileSize, int maxFractionDigits)
- Parameters:
fileSize- in bytesmaxFractionDigits- maximum number of fraction digits- Returns:
- file size as a human friendly string.
-
parseFileSize
public static long parseFileSize(@NotNull String fileSizeStr) throws NumberFormatExceptionParses file size from string. String can have different suffixes, like, kb, mb, tb, etc.- Parameters:
fileSizeStr- string to parse- Returns:
- actual file size in bytes
- Throws:
NumberFormatException- if parsing fails- Since:
- 8.0.3
-
processLines
public static void processLines(@NotNull InputStream in, @NotNull StringUtil.LineProcessor processor) throws IOException- Throws:
IOException
-
processLines
public static void processLines(@NotNull File file, @NotNull StringUtil.LineProcessor processor) throws IOException- Throws:
IOException
-
escapeStr
@Deprecated public static String escapeStr(String str, StringUtil.EscapeInfoProvider p)
Escapes characters specified by provider with '\' and specified character.- Parameters:
str- initial stringp- escape info provider.- Returns:
- escaped string.
-
escapeStr
public static String escapeStr(String str, StringUtil.EscapeInfoProvider2 p)
Escapes characters specified by provider with '\' and specified character.- Parameters:
str- initial stringp- escape info provider.- Returns:
- escaped string.
-
unescapeStr
@Deprecated public static String unescapeStr(String str, StringUtil.EscapeInfoProvider p)
Unescapes characters specified by provider with '\' and specified character.- Parameters:
str- initial stringp- escape info provider.- Returns:
- unescaped string.
-
unescapeStr
public static String unescapeStr(String str, StringUtil.EscapeInfoProvider2 p)
Unescapes characters specified by provider with '\' and specified character.- Parameters:
str- initial stringp- escape info provider.- Returns:
- unescaped string.
-
encodeURLParameter
@Nullable @Contract("null,_->null;!null,_->!null") public static String encodeURLParameter(@Nullable String source, @NotNull String encoding) throws UnsupportedEncodingExceptionEncode the given URL query parameter with the given encoding.- Parameters:
source- the String to be encodedencoding- the character encoding to encode to- Returns:
- the encoded String
- Throws:
UnsupportedEncodingException- when the given encoding parameter is not supported
-
encodeURLParameter
@Nullable @Contract("null->null;!null->!null") public static String encodeURLParameter(@Nullable String source)Encode the given URL query parameter with the given encoding.- Parameters:
source- the String to be encoded- Returns:
- the encoded String
-
decodeURL
@Nullable @Contract("null,_->null;!null,_->!null") public static String decodeURL(@Nullable String source, @NotNull String encoding) throws UnsupportedEncodingExceptionCopied from org.springframework.web.util.UriUtils#decode Copied to not include whole spring package to modules where only UriUtils#decodeURL is neededUse this method instead of URLDecoder.decode when decoding urls, as URLDecoder is not handling '+' properly See TW-49982 and https://bugs.openjdk.java.net/browse/JDK-8179507 for more info
- Alphanumeric characters
"a"through"z","A"through"Z", and"0"through"9"stay the same. - Special characters
"-","_",".", and"*"stay the same. - A sequence "
%<i>xy</i>" is interpreted as a hexadecimal representation of the character.
- Parameters:
source- encoded Stringencoding- encoding- Returns:
- decoded value
- Throws:
IllegalArgumentException- when the given source contains invalid encoded sequencesUnsupportedEncodingException- when the given encoding parameter is not supported
- Alphanumeric characters
-
decodeURL
@Nullable @Contract("null->null;!null->!null") public static String decodeURL(@Nullable String source)
-
escapeForCSV
@NotNull public static String escapeForCSV(@NotNull String s)
Escapes the value to be used in a CSV row.- Fields with embedded commas must be delimited with double-quote characters - Fields that contain double quote characters must be surounded by double-quotes, and the embedded double-quotes must each be represented by a pair of consecutive double quotes - A field that contains embedded line-breaks must be surounded by double-quotes
- Parameters:
s- the string to escape- Returns:
- escaped string
-
formatTextForWeb
public static String formatTextForWeb(String txt)
Formats text for showing on the web page preserving original text formatting. Dangerous characters like < will be replaced with corresponding entities, line feeds will be replaced with br tag- Parameters:
txt- initial text- Returns:
- text ready for publishing on Web page
-
withPlural
@NotNull public static String withPlural(long n, @NotNull String base)
Returns duly pluralized form of "N items" text
-
replaceNonAlphaNumericChars
public static String replaceNonAlphaNumericChars(String originalStr, char toReplace)
Replaces all characters except A-Za-z0-9_ to specified character.- Parameters:
originalStr- original stringtoReplace- character to replace with- Returns:
- string with replaced characters
-
peekNthDelimitedField
@Nullable @Contract("null, _, _, _ -> null; !null, _, _, _ -> !null") public static String peekNthDelimitedField(@Nullable String string, char separator, int nth, boolean trim)Treats the given string as a separator delimited string, and returns the nth field from this string.- Parameters:
string- delimited string; nulls are allowed.separator- fields separator.nth- number of filed to return; the first filed is 1, the second field is 2, etc; 0 not allowed.trim- determines whether this function apply trim() before returning the field.- Returns:
- the nth field, or an empty string if not found, or null if the given string is null.
- Since:
- 5.0
-
charAt
public static char charAt(@Nullable String string, int position)Returns the n-th character of the string. if the given string is null or too short, '\0' is returned.- Parameters:
string- the string which character to return.position- character position, starts with 0.- Returns:
- the specified character, or '\0'.
-
nullIfEmpty
@Contract("null -> null") @Nullable public static String nullIfEmpty(@Nullable String string)Returns given string if it is not empty, or null if it is empty.- Parameters:
string- string to check for be empty.- Returns:
- non-empty given string or null.
- Since:
- 5.0
-
emptyIfNull
@NotNull public static String emptyIfNull(@Nullable String string)
Returns given string if it is not null, or empty string if a null given.- Parameters:
string- string to check for be a null.- Returns:
- given string or an empty string if a null is given
- Since:
- 5.0
-
notEmpty
@NotNull public static String notEmpty(@Nullable String string, @NotNull String defaultValue)
Returns either given string, or if it is null or empty, thedefaultValue.- Parameters:
string- string to check for be a null or empty.- Returns:
- given string or the defaultValue
- Since:
- 8.1
-
trim
@Nullable @Contract("null->null; !null->!null") public static String trim(@Nullable String s)Returns the trimmed string, ornull- Parameters:
s- input string- Returns:
- trimmer string, or
null - Since:
- 7.1
-
trimAndNull
@Nullable @Contract("null -> null") public static String trimAndNull(@Nullable String string)Trims the given string and returns it if after trimming if is not empty; otherwise returns null.- Parameters:
string- source string.- Returns:
- trimmed non-empty string or null.
- Since:
- 6.5
-
trimRight
@Nullable @Contract("null->null;!null->!null") public static String trimRight(@Nullable String string)Removes the right (end) spaces from the string.- Parameters:
string- string to trim; nulls and empty strings are allowed.- Returns:
- the string without right spaces, or null if null given.
-
trimStringBuilderLeft
public static void trimStringBuilderLeft(@NotNull StringBuilder buf)Removes starting spaces.- Parameters:
buf- buf to remove from.- Since:
- 5.0
-
stripLeftAndRight
@NotNull public static String stripLeftAndRight(@NotNull String s, @NotNull CharFilter filter)
Returns the stringsstripped from the beginning and end with symbols matched byfilter. E.g.stripLeftAndRight(" foo bar \n", CharFilter.WHITESPACE_FILTER) == "foo bar".- Parameters:
s- the input stringfilter- char filter- Returns:
- a stripped string
-
elapsedTimeToString
@NotNull public static String elapsedTimeToString(long millis)
-
millisToString
@NotNull public static String millisToString(long timeIntervalMs, boolean useMillis)
-
formatInt
@NotNull public static String formatInt(int value, int length, char fillChar)
-
formatInt
@NotNull public static String formatInt(int value, int length)
-
formatInt
@NotNull public static String formatInt(int value)
-
splitHonorQuotes
@NotNull public static List<String> splitHonorQuotes(@NotNull String s, char separator)
-
substringByRegex
public static String substringByRegex(CharSequence text, Pattern pattern, int groupNr)
Gets the inner part of string that specified with the regular expression.This function looks for the first occurrence of the specified pattern in the given text, and return the content matched the n-th groups of the regular expression.
For example, if text = "aaa bbbcccddd eee bbccdd xxx", pattern = "b+(c+)d+" and n = 1, the result will be "ccc".
- Parameters:
text- text to look through; can be null.pattern- pattern, must contains at least one group (one pair of parentheses); not null.groupNr- number of the group to return, started from 1, or 0 for return a string matched for the whole pattern.- Returns:
- substring matched to the n-th group, or null if not matched at all.
- Since:
- 6.0
-
stringValueOf
@NotNull public static String stringValueOf(@Nullable Object obj, @NotNull String defaultValue)
-
collapseSpaces
public static String collapseSpaces(@NotNull String str)
Replaces a sequence of space characters with single whitespace.- Parameters:
str- string where to collapse spaces- Returns:
- string with collapsed spaces
- Since:
- 7.0
-
replaceNewLines
public static String replaceNewLines(@NotNull String str, @NotNull String replacement)
- Parameters:
str- string to transform- Returns:
- replaces sequences of new line characters with single occurrence of replacement string.
- Since:
- 2018.2
-
newLineToSpaceDelimited
public static String newLineToSpaceDelimited(@NotNull String str)
- Parameters:
str- string to transform- Returns:
- replaces sequences of new lines with single space. Resulted string is trimmed.
- Since:
- 7.0
-
hasParameterReferences
public static boolean hasParameterReferences(@Nullable String str)Returns true if string contains parameter references of form %param.name% This method is equals toReferencesResolverUtil.containsReference(java.lang.String, java.lang.String[], boolean)with args (str, new String[0], true), except str nullability.- Parameters:
str- string to check- Returns:
- see above
-
removeNonBMPCharacters
@NotNull public static String removeNonBMPCharacters(@NotNull String str)
Replaces all non-BMP characters with the sign character.If the string doesn't contain non-BMP characters, the result is exactly the input string (you can check it using ==).
The method is optimized for performance.
- Parameters:
str- string where to remove non-BMP characters- Returns:
- the string without BMP characters.
- Since:
- 7.1.5
-
hasNonBMPCharacters
public static boolean hasNonBMPCharacters(@NotNull String str)
-
objectToString
@Nullable @Contract("null -> null") public static String objectToString(@Nullable Object object)Safely callsObject.toString().- Parameters:
object- object- Returns:
- return result of object toString() if object is not null or returns null
-
splitLines
@NotNull public static String[] splitLines(@NotNull String string)
Splits the string by lines. Does not remove any leading/trailing spaces.- See Also:
StringUtil.splitByLines(String)
-
convertCamelToDashSeparated
@Contract("null -> null") public static String convertCamelToDashSeparated(@Nullable String camelCasedString)
-
convertCamelToSpaceSeparated
@Contract("null -> null") public static String convertCamelToSpaceSeparated(@Nullable String camelCasedString)
-
-