Class StringUtil


  • public class StringUtil
    extends com.intellij.openapi.util.text.StringUtil
    Author:
    Kir
    • Method Summary

      All Methods Static Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      static boolean areEqual​(java.lang.String string1, java.lang.String string2)
      Checks whether two given strings are equal.
      static boolean areEqualIgnoringCase​(java.lang.String string1, java.lang.String string2)
      Checks whether two given strings are equal, ignoring characters case.
      static java.lang.String biteOffPostfix​(java.lang.String line, java.lang.String postfix)  
      static char charAt​(java.lang.String string, int position)
      Returns the n-th character of the string.
      static java.lang.String collapseSpaces​(java.lang.String str)
      Replaces a sequence of space characters with single whitespace.
      static int compare​(java.lang.String s1, java.lang.String s2)  
      static java.lang.String convertAndCollapseSlashes​(java.lang.String s)
      Replaces backslashes with forward and collapse consequent slashes into one.
      static void convertStringsToLowerCase​(java.util.List<java.lang.String> strings)
      Converts all strings inside the given list to lower case.
      static java.lang.String convertWildcardToRegexp​(java.lang.String pattern)
      Converts pattern with wildcards (* or ?) to regular expression.
      static java.util.Iterator<java.lang.String> createEscapedTokenizer​(java.lang.String string, char del)
      Split string into tokens, ignores delimiters with escaping ('\')
      static java.lang.String dateToString​(java.util.Date date)  
      static java.lang.String decodeURL​(java.lang.String source)  
      static java.lang.String decodeURL​(java.lang.String source, java.lang.String encoding)
      Copied from org.springframework.web.util.UriUtils#decode Copied to not include whole spring package to modules where only UriUtils#decodeURL is needed
      static boolean differCaseOnly​(java.lang.String string1, java.lang.String string2)
      Checks that the two given strings are different but differ in their case only.
      static java.lang.String doubleQuote​(java.lang.String string)
      Quotes the string with double quotes.
      static java.lang.String elapsedTimeToString​(long millis)  
      static java.lang.String elapsedTimeToString​(java.util.Date date)  
      static java.lang.String emptyIfNull​(java.lang.String string)
      Returns given string if it is not null, or empty string if a null given.
      static java.lang.String encodeURLParameter​(java.lang.String source)
      Encode the given URL query parameter with the given encoding.
      static java.lang.String encodeURLParameter​(java.lang.String source, java.lang.String encoding)
      Encode the given URL query parameter with the given encoding.
      static void escapeDataForCSV​(java.io.Writer writer, java.lang.String... data)  
      static java.lang.String escapeForCSV​(java.lang.String s)
      Escapes the value to be used in a CSV row.
      static java.lang.String escapeForCSV​(java.lang.String... data)  
      static java.lang.String escapeForRegex​(java.lang.String str)
      Converts string to a form which is safe to use for regular expressions.
      static java.lang.String escapeHTML​(java.lang.String text, boolean replaceQuotes)  
      static java.lang.String escapeQuotesIfWindows​(java.lang.String value)  
      static java.lang.String escapeStr​(java.lang.String str, StringUtil.EscapeInfoProvider p)
      static java.lang.String escapeStr​(java.lang.String str, StringUtil.EscapeInfoProvider2 p)
      Escapes characters specified by provider with '\' and specified character.
      static int findInvalidXMLChar​(java.lang.String value)
      Deprecated.
      static int findInvalidXMLCodePoint​(java.lang.String value)
      Looks for Unicode code points that cannot be presented in XML.
      static java.lang.String formatFileSize​(long fileSize)  
      static java.lang.String formatFileSize​(long fileSize, int maxFractionDigits)  
      static java.lang.String formatFileSize​(java.io.File file)  
      static java.lang.String formatInt​(int value)  
      static java.lang.String formatInt​(int value, int length)  
      static java.lang.String formatInt​(int value, int length, char fillChar)  
      static java.lang.String formatPercent​(float numerator, long denominator)  
      static java.lang.String formatTextForWeb​(java.lang.String txt)
      Formats text for showing on the web page preserving original text formatting.
      static java.lang.String generateUniqueHash()
      NOTE: This could take more than 30 seconds for the first call Generates unique hash value.
      static java.lang.String generateUniqueHashQuickly()
      Quickly returns non-secure random hash value
      static java.lang.String getOrdinal​(int number)
      Return ordinal ending for a number, i.e.
      static boolean hasNonBMPCharacters​(java.lang.String str)  
      static boolean hasParameterReferences​(java.lang.String str)
      Returns true if string contains parameter references of form %param.name% This method is equals to ReferencesResolverUtil.containsReference(java.lang.String, java.lang.String[], boolean) with args (str, new String[0], true), except str nullability.
      static int indexOf​(java.lang.String currentString, char findWhat, StringUtil.EscapeInfoProvider escaper)
      static int indexOf​(java.lang.String currentString, char findWhat, StringUtil.EscapeInfoProvider2 escaper)  
      static boolean isAPositiveNumber​(java.lang.String value)  
      static boolean isNumber​(java.lang.String value)  
      static boolean isTrue​(java.lang.String property)  
      static boolean isUpperCase​(java.lang.String str)
      Check whether the string is uppercase: contains at least one uppercase letter and no lowercase letters.
      static boolean isValidXMLChar​(char c)
      Deprecated.
      Please use isValidXMLCodePoint(int) instead.
      Section 2.2 of the XML spec describes which Unicode code points are valid in XML:
      static boolean isValidXMLCodePoint​(int c)
      Section 2.2 of the XML spec describes which Unicode code points are valid in XML:
      static java.lang.String join​(java.lang.String separator, java.lang.Iterable toJoin)
      Simple string joiner with given separator.
      static void join​(java.lang.String separator, java.lang.Iterable toJoin, java.lang.StringBuilder result)
      Simple string joiner with given separator.
      static java.lang.String join​(java.lang.String separator, java.lang.Object... toJoin)
      Simple string joiner with given separator.
      static java.lang.String lastPartOf​(java.lang.String s, char separator)  
      static java.lang.String millisToString​(long timeIntervalMs, boolean useMillis)  
      static java.lang.String newLineToSpaceDelimited​(java.lang.String str)  
      static java.lang.String notEmpty​(java.lang.String string, java.lang.String defaultValue)
      Returns either given string, or if it is null or empty, the defaultValue.
      static java.lang.String nullIfEmpty​(java.lang.String string)
      Returns given string if it is not empty, or null if it is empty.
      static java.lang.String objectToString​(java.lang.Object object)
      Safely calls Object.toString().
      static long parseFileSize​(java.lang.String fileSizeStr)
      Parses file size from string.
      static java.lang.String peekNthDelimitedField​(java.lang.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 void processLines​(java.io.File file, StringUtil.LineProcessor processor)  
      static void processLines​(java.io.InputStream in, StringUtil.LineProcessor processor)  
      static void processLines​(java.lang.String str, StringUtil.LineProcessor processor)  
      static java.lang.String propertiesToString​(java.util.Map<java.lang.String,​java.lang.String> props, StringUtil.EscapeInfoProvider escaper)
      static java.lang.String propertiesToString​(java.util.Map<java.lang.String,​java.lang.String> props, StringUtil.EscapeInfoProvider2 escaper)  
      static java.lang.String removeLeadingAndTailingSlash​(java.lang.String path)
      Combines #removeLeadingSlash and #removeTailingSlash
      static java.lang.String removeLeadingSlash​(java.lang.String path)
      If given string starts with /, remove it and return remaining string
      static java.lang.String removeNonBMPCharacters​(java.lang.String str)
      Replaces all non-BMP characters with the sign character.
      static java.lang.String removeSuffix​(java.lang.String string, java.lang.String suffix, boolean caseSensitive)
      If the given string ends with the specified suffix, removes it.
      static java.lang.String removeTailingSlash​(java.lang.String path)
      If given string ends with /, remove it and return remaining string
      static java.lang.String repeat​(java.lang.String whatRepeat, java.lang.String separator, int times)  
      static void repeat​(java.lang.String whatRepeat, java.lang.String separator, int times, java.lang.StringBuilder builder)  
      static void replace​(java.lang.StringBuilder buf, java.lang.String what, java.lang.String with)
      Replaces all occurrences of the what substring with the with in the specified string buffer.
      static void replace​(java.lang.StringBuilder buf, java.util.regex.Pattern pattern, java.lang.String with)
      Replaces all occurrences of the pattern with the with string in the specified string buffer.
      static java.lang.String replaceInvalidXmlChars​(java.lang.String str)
      Replaces all unicode code points illegal in xml with spaces
      static java.lang.String replaceNewLines​(java.lang.String str, java.lang.String replacement)  
      static java.lang.String replaceNonAlphaNumericChars​(java.lang.String originalStr, char toReplace)
      Replaces all characters except A-Za-z0-9_ to specified character.
      static java.util.regex.Pattern searchByKeywordPattern​(java.lang.String keyword, boolean caseInsensitive)
      Returns RegEx pattern to search by specified keyword.
      static java.util.List<java.lang.String> split​(java.lang.String values)
      Splits values using default separators, note that empty strings are then removed from the result.
      static java.util.List<java.lang.String> split​(java.lang.String values, boolean removeEmpty, char... separators)
      Splits values using specified separators, empty strings are preserved.
      static java.util.List<java.lang.String> splitCommandArgumentsAndUnquote​(java.lang.String line)
      This utility differs from splitHonorQuote: it considers quote in sequence 'ddd\" -' as boundary quote.
      static java.util.List<java.lang.String> splitHonorQuotes​(java.lang.String s)  
      static java.util.List<java.lang.String> splitHonorQuotes​(java.lang.String s, char separator)  
      static java.lang.String[] splitLines​(java.lang.String string)
      Splits the string by lines.
      static java.lang.String stackTrace​(java.lang.Throwable exception)  
      static java.util.Map<java.lang.String,​java.lang.String> stringToProperties​(java.lang.String string, StringUtil.EscapeInfoProvider escaper)
      static java.util.Map<java.lang.String,​java.lang.String> stringToProperties​(java.lang.String string, StringUtil.EscapeInfoProvider2 escaper)
      performs conversion of string to property map with string name checking.
      static java.util.Map<java.lang.String,​java.lang.String> stringToProperties​(java.lang.String string, StringUtil.EscapeInfoProvider2 escaper, boolean strictNameCheck)
      Converts string to property map
      static java.util.Map<java.lang.String,​java.lang.String> stringToProperties​(java.lang.String string, StringUtil.EscapeInfoProvider escaper, boolean strictNameCheck)
      static java.lang.String stringValueOf​(java.lang.Object obj, java.lang.String defaultValue)  
      static java.lang.String stripLeftAndRight​(java.lang.String s, com.intellij.openapi.util.text.CharFilter filter)
      Returns the string s stripped from the beginning and end with symbols matched by filter.
      static java.lang.String substringByRegex​(java.lang.CharSequence text, java.util.regex.Pattern pattern, int groupNr)
      Gets the inner part of string that specified with the regular expression.
      static java.lang.String trim​(java.lang.String s)
      Returns the trimmed string, or null
      static java.lang.String trimAndNull​(java.lang.String string)
      Trims the given string and returns it if after trimming if is not empty; otherwise returns null.
      static java.lang.String trimRight​(java.lang.String string)
      Removes the right (end) spaces from the string.
      static void trimStringBuilderLeft​(java.lang.StringBuilder buf)
      Removes starting spaces.
      static java.lang.String truncateStringValue​(java.lang.String str, int maxLength)
      Truncates string, returns part of the initial string with length up to max length characters.
      static java.lang.String truncateStringValueWithDotsAtCenter​(java.lang.String str, int maxLength)
      Truncates string and adds dots to the center of the string if it was truncated.
      static java.lang.String truncateStringValueWithDotsAtEnd​(java.lang.String str, int maxLength)
      Truncates string and adds dots to the end of the string if it was truncated.
      static java.lang.String unescapeStr​(java.lang.String str, StringUtil.EscapeInfoProvider p)
      static java.lang.String unescapeStr​(java.lang.String str, StringUtil.EscapeInfoProvider2 p)
      Unescapes characters specified by provider with '\' and specified character.
      static java.lang.String withPlural​(long n, java.lang.String base)
      Returns duly pluralized form of "N items" text
      • Methods inherited from class com.intellij.openapi.util.text.StringUtil

        assertValidSeparators, 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, 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
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • areEqual

        @Contract("null, null -> true")
        public static boolean areEqual​(@Nullable
                                       java.lang.String string1,
                                       @Nullable
                                       java.lang.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
                                                   java.lang.String string1,
                                                   @Nullable
                                                   java.lang.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
                                             java.lang.String string1,
                                             @NotNull
                                             java.lang.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
                                          java.lang.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
      • escapeHTML

        @NotNull
        public static java.lang.String escapeHTML​(@Nullable
                                                  java.lang.String text,
                                                  boolean replaceQuotes)
      • splitCommandArgumentsAndUnquote

        @NotNull
        public static java.util.List<java.lang.String> splitCommandArgumentsAndUnquote​(@NotNull
                                                                                       java.lang.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 java.lang.String biteOffPostfix​(@NotNull
                                                      java.lang.String line,
                                                      @NotNull
                                                      java.lang.String postfix)
      • lastPartOf

        @NotNull
        public static java.lang.String lastPartOf​(@NotNull
                                                  java.lang.String s,
                                                  char separator)
      • truncateStringValue

        @Nullable
        @Contract("null, _ -> null; !null, _ -> !null")
        public static java.lang.String truncateStringValue​(@Nullable
                                                           java.lang.String str,
                                                           int maxLength)
        Truncates string, returns part of the initial string with length up to max length characters.
        Parameters:
        str - string to truncate
        maxLength - max length
        Returns:
        see above
      • truncateStringValueWithDotsAtEnd

        @Nullable
        @Contract("null, _ -> null; !null, _ -> !null")
        public static java.lang.String truncateStringValueWithDotsAtEnd​(@Nullable
                                                                        java.lang.String str,
                                                                        int maxLength)
        Truncates string and adds dots to the end of the string if it was truncated.
        Parameters:
        str - string to truncate
        maxLength - max length of the resulting string
        Returns:
        truncated string with dots at the end
      • truncateStringValueWithDotsAtCenter

        @Nullable
        @Contract("null, _ -> null; !null, _ -> !null")
        public static java.lang.String truncateStringValueWithDotsAtCenter​(@Nullable
                                                                           java.lang.String str,
                                                                           int maxLength)
        Truncates string and adds dots to the center of the string if it was truncated.
        Parameters:
        str - string to truncate
        maxLength - 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:

        #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

        Code points outside this set cannot be represented in XML.

        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 use isValidXMLCodePoint(int) instead.
        Section 2.2 of the XML spec describes which Unicode code points are valid in XML:

        #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

        Code points outside this set cannot be represented in XML.

        Parameters:
        c - The character to inspect.
        Returns:
        Whether the specified character is valid in XML.
      • findInvalidXMLCodePoint

        public static int findInvalidXMLCodePoint​(@NotNull
                                                  java.lang.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 use replaceInvalidXmlChars(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
                                             java.lang.String value)
        Deprecated.
        Please use findInvalidXMLCodePoint(String) instead. Looks for characters that cannot be presented in XML To ensure that given string does not contain illegal characters please use replaceInvalidXmlChars(String).
        Parameters:
        value - value
        Returns:
        index of invalid XML character in the string or -1 if all chars are valid
      • replaceInvalidXmlChars

        @NotNull
        public static java.lang.String replaceInvalidXmlChars​(@NotNull
                                                              java.lang.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 java.lang.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 java.lang.String generateUniqueHashQuickly()
        Quickly returns non-secure random hash value
        Returns:
        see above
        Since:
        8.1
      • searchByKeywordPattern

        @NotNull
        public static java.util.regex.Pattern searchByKeywordPattern​(@NotNull
                                                                     java.lang.String keyword,
                                                                     boolean caseInsensitive)
        Returns RegEx pattern to search by specified keyword.
        Parameters:
        keyword - keyword
        caseInsensitive - is case sensitive
        Returns:
        pattern to match it
      • escapeForRegex

        @NotNull
        public static java.lang.String escapeForRegex​(@NotNull
                                                      java.lang.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 java.lang.String convertWildcardToRegexp​(@NotNull
                                                               java.lang.String pattern)
        Converts pattern with wildcards (* or ?) to regular expression.
        Parameters:
        pattern - pattern
        Returns:
        regexp
      • split

        @NotNull
        public static java.util.List<java.lang.String> split​(@NotNull
                                                             java.lang.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 java.util.List<java.lang.String> split​(@NotNull
                                                             java.lang.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 split
        removeEmpty - if true then empty strings will not be returned
        separators - separators
        Returns:
        list of splitted values (with empty strings possible)
      • isAPositiveNumber

        @Contract("null -> false")
        public static boolean isAPositiveNumber​(@Nullable
                                                java.lang.String value)
      • isNumber

        @Contract("null -> false")
        public static boolean isNumber​(@Nullable
                                       java.lang.String value)
      • getOrdinal

        @NotNull
        public static java.lang.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
      • stackTrace

        @NotNull
        public static java.lang.String stackTrace​(@NotNull
                                                  java.lang.Throwable exception)
      • join

        @NotNull
        public static java.lang.String join​(@Nullable
                                            java.lang.String separator,
                                            @NotNull
                                            java.lang.Iterable toJoin)
        Simple string joiner with given separator. Null values are ignored
        Parameters:
        separator - separator for joined string
        toJoin - object to join, if an object is null, it is ignored
        Returns:
        joined string
        Since:
        5.0
      • join

        public static void join​(@Nullable
                                java.lang.String separator,
                                @NotNull
                                java.lang.Iterable toJoin,
                                @NotNull
                                java.lang.StringBuilder result)
        Simple string joiner with given separator. Null values are ignored
        Parameters:
        separator - separator for joined string
        toJoin - object to join, if an object is null, it is ignored
        result - string builder to put result to
        Since:
        5.0
      • join

        @NotNull
        public static java.lang.String join​(@Nullable
                                            java.lang.String separator,
                                            @NotNull
                                            java.lang.Object... toJoin)
        Simple string joiner with given separator. Null values are ignored
        Parameters:
        separator - separator for joined string
        toJoin - object to join, if an object is null, it is ignored
        Returns:
        joined string
        Since:
        5.0
      • doubleQuote

        @NotNull
        public static java.lang.String doubleQuote​(@NotNull
                                                   java.lang.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 java.util.Iterator<java.lang.String> createEscapedTokenizer​(java.lang.String string,
                                                                                  char del)
        Split string into tokens, ignores delimiters with escaping ('\')
        Parameters:
        string - string data to tokenize
        del - selimiter
        Returns:
        result iterator
      • stringToProperties

        @Deprecated
        @NotNull
        public static java.util.Map<java.lang.String,​java.lang.String> stringToProperties​(@NotNull
                                                                                                java.lang.String string,
                                                                                                @NotNull
                                                                                                StringUtil.EscapeInfoProvider escaper,
                                                                                                boolean strictNameCheck)
                                                                                         throws java.text.ParseException
        Converts string to property map
        Parameters:
        string - in a form of "name1='value' name2='value' ..."
        escaper - escaping rule provider
        strictNameCheck - 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:
        java.text.ParseException - if parsing of the property sting failed
      • stringToProperties

        @NotNull
        public static java.util.Map<java.lang.String,​java.lang.String> stringToProperties​(@NotNull
                                                                                                java.lang.String string,
                                                                                                @NotNull
                                                                                                StringUtil.EscapeInfoProvider2 escaper,
                                                                                                boolean strictNameCheck)
                                                                                         throws java.text.ParseException
        Converts string to property map
        Parameters:
        string - in a form of "name1='value' name2='value' ..."
        escaper - escaping rule provider
        strictNameCheck - 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:
        java.text.ParseException - if parsing of the property sting failed
      • propertiesToString

        public static java.lang.String propertiesToString​(java.util.Map<java.lang.String,​java.lang.String> props,
                                                          StringUtil.EscapeInfoProvider2 escaper)
      • repeat

        public static java.lang.String repeat​(java.lang.String whatRepeat,
                                              java.lang.String separator,
                                              int times)
      • repeat

        public static void repeat​(java.lang.String whatRepeat,
                                  java.lang.String separator,
                                  int times,
                                  java.lang.StringBuilder builder)
      • isTrue

        @Contract("null -> false")
        public static boolean isTrue​(@Nullable
                                     java.lang.String property)
      • escapeQuotesIfWindows

        public static java.lang.String escapeQuotesIfWindows​(java.lang.String value)
      • convertStringsToLowerCase

        public static void convertStringsToLowerCase​(@NotNull
                                                     java.util.List<java.lang.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 java.lang.String removeTailingSlash​(@Nullable
                                                          java.lang.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 java.lang.String removeSuffix​(@NotNull
                                                    java.lang.String string,
                                                    @NotNull
                                                    java.lang.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 java.lang.String removeLeadingSlash​(@Nullable
                                                          java.lang.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 java.lang.String removeLeadingAndTailingSlash​(@Nullable
                                                                    java.lang.String path)
        Combines #removeLeadingSlash and #removeTailingSlash
        Parameters:
        path - input string
        Returns:
        see above
        Since:
        8.0
      • replace

        public static void replace​(@NotNull
                                   java.lang.StringBuilder buf,
                                   @NotNull
                                   java.lang.String what,
                                   @NotNull
                                   java.lang.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
                                   java.lang.StringBuilder buf,
                                   @NotNull
                                   java.util.regex.Pattern pattern,
                                   @NotNull
                                   java.lang.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.
      • compare

        public static int compare​(@Nullable
                                  java.lang.String s1,
                                  @Nullable
                                  java.lang.String s2)
      • convertAndCollapseSlashes

        @NotNull
        public static java.lang.String convertAndCollapseSlashes​(@NotNull
                                                                 java.lang.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
                                        java.lang.String str,
                                        @NotNull
                                        StringUtil.LineProcessor processor)
                                 throws java.io.IOException
        Throws:
        java.io.IOException
      • formatPercent

        @NotNull
        public static java.lang.String formatPercent​(float numerator,
                                                     long denominator)
      • formatFileSize

        @NotNull
        public static java.lang.String formatFileSize​(java.io.File file)
        Returns:
        file size as a human friendly string.
        Since:
        9.0
      • formatFileSize

        @NotNull
        public static java.lang.String formatFileSize​(long fileSize)
        Parameters:
        fileSize - in bytes
        Returns:
        file size as a human friendly string.
      • formatFileSize

        @NotNull
        public static java.lang.String formatFileSize​(long fileSize,
                                                      int maxFractionDigits)
        Parameters:
        fileSize - in bytes
        maxFractionDigits - maximum number of fraction digits
        Returns:
        file size as a human friendly string.
      • parseFileSize

        public static long parseFileSize​(@NotNull
                                         java.lang.String fileSizeStr)
                                  throws java.lang.NumberFormatException
        Parses 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:
        java.lang.NumberFormatException - if parsing fails
        Since:
        8.0.3
      • processLines

        public static void processLines​(@NotNull
                                        java.io.InputStream in,
                                        @NotNull
                                        StringUtil.LineProcessor processor)
                                 throws java.io.IOException
        Throws:
        java.io.IOException
      • processLines

        public static void processLines​(@NotNull
                                        java.io.File file,
                                        @NotNull
                                        StringUtil.LineProcessor processor)
                                 throws java.io.IOException
        Throws:
        java.io.IOException
      • escapeStr

        public static java.lang.String escapeStr​(java.lang.String str,
                                                 StringUtil.EscapeInfoProvider2 p)
        Escapes characters specified by provider with '\' and specified character.
        Parameters:
        str - initial string
        p - escape info provider.
        Returns:
        escaped string.
      • unescapeStr

        public static java.lang.String unescapeStr​(java.lang.String str,
                                                   StringUtil.EscapeInfoProvider2 p)
        Unescapes characters specified by provider with '\' and specified character.
        Parameters:
        str - initial string
        p - escape info provider.
        Returns:
        unescaped string.
      • encodeURLParameter

        @Nullable
        @Contract("null,_->null;!null,_->!null")
        public static java.lang.String encodeURLParameter​(@Nullable
                                                          java.lang.String source,
                                                          @NotNull
                                                          java.lang.String encoding)
                                                   throws java.io.UnsupportedEncodingException
        Encode the given URL query parameter with the given encoding.
        Parameters:
        source - the String to be encoded
        encoding - the character encoding to encode to
        Returns:
        the encoded String
        Throws:
        java.io.UnsupportedEncodingException - when the given encoding parameter is not supported
      • encodeURLParameter

        @Nullable
        @Contract("null->null;!null->!null")
        public static java.lang.String encodeURLParameter​(@Nullable
                                                          java.lang.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 java.lang.String decodeURL​(@Nullable
                                                 java.lang.String source,
                                                 @NotNull
                                                 java.lang.String encoding)
                                          throws java.io.UnsupportedEncodingException
        Copied from org.springframework.web.util.UriUtils#decode Copied to not include whole spring package to modules where only UriUtils#decodeURL is needed

        Use 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 String
        encoding - encoding
        Returns:
        decoded value
        Throws:
        java.lang.IllegalArgumentException - when the given source contains invalid encoded sequences
        java.io.UnsupportedEncodingException - when the given encoding parameter is not supported
      • decodeURL

        @Nullable
        @Contract("null->null;!null->!null")
        public static java.lang.String decodeURL​(@Nullable
                                                 java.lang.String source)
      • escapeForCSV

        @NotNull
        public static java.lang.String escapeForCSV​(@NotNull
                                                    java.lang.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 java.lang.String formatTextForWeb​(java.lang.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 java.lang.String withPlural​(long n,
                                                  @NotNull
                                                  java.lang.String base)
        Returns duly pluralized form of "N items" text
      • replaceNonAlphaNumericChars

        public static java.lang.String replaceNonAlphaNumericChars​(java.lang.String originalStr,
                                                                   char toReplace)
        Replaces all characters except A-Za-z0-9_ to specified character.
        Parameters:
        originalStr - original string
        toReplace - character to replace with
        Returns:
        string with replaced characters
      • peekNthDelimitedField

        @Nullable
        @Contract("null, _, _, _ -> null; !null, _, _, _ -> !null")
        public static java.lang.String peekNthDelimitedField​(@Nullable
                                                             java.lang.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
                                  java.lang.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 java.lang.String nullIfEmpty​(@Nullable
                                                   java.lang.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 java.lang.String emptyIfNull​(@Nullable
                                                   java.lang.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 java.lang.String notEmpty​(@Nullable
                                                java.lang.String string,
                                                @NotNull
                                                java.lang.String defaultValue)
        Returns either given string, or if it is null or empty, the defaultValue.
        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 java.lang.String trim​(@Nullable
                                            java.lang.String s)
        Returns the trimmed string, or null
        Parameters:
        s - input string
        Returns:
        trimmer string, or null
        Since:
        7.1
      • trimAndNull

        @Nullable
        @Contract("null -> null")
        public static java.lang.String trimAndNull​(@Nullable
                                                   java.lang.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 java.lang.String trimRight​(@Nullable
                                                 java.lang.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
                                                 java.lang.StringBuilder buf)
        Removes starting spaces.
        Parameters:
        buf - buf to remove from.
        Since:
        5.0
      • stripLeftAndRight

        @NotNull
        public static java.lang.String stripLeftAndRight​(@NotNull
                                                         java.lang.String s,
                                                         @NotNull
                                                         com.intellij.openapi.util.text.CharFilter filter)
        Returns the string s stripped from the beginning and end with symbols matched by filter.

        E.g. stripLeftAndRight(" foo bar \n", CharFilter.WHITESPACE_FILTER) == "foo bar".

        Parameters:
        s - the input string
        filter - char filter
        Returns:
        a stripped string
      • elapsedTimeToString

        @NotNull
        public static java.lang.String elapsedTimeToString​(@Nullable
                                                           java.util.Date date)
      • elapsedTimeToString

        @NotNull
        public static java.lang.String elapsedTimeToString​(long millis)
      • millisToString

        @NotNull
        public static java.lang.String millisToString​(long timeIntervalMs,
                                                      boolean useMillis)
      • dateToString

        @NotNull
        public static java.lang.String dateToString​(@NotNull
                                                    java.util.Date date)
      • formatInt

        @NotNull
        public static java.lang.String formatInt​(int value,
                                                 int length,
                                                 char fillChar)
      • formatInt

        @NotNull
        public static java.lang.String formatInt​(int value,
                                                 int length)
      • formatInt

        @NotNull
        public static java.lang.String formatInt​(int value)
      • splitHonorQuotes

        @NotNull
        public static java.util.List<java.lang.String> splitHonorQuotes​(@NotNull
                                                                        java.lang.String s,
                                                                        char separator)
      • substringByRegex

        public static java.lang.String substringByRegex​(java.lang.CharSequence text,
                                                        java.util.regex.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
      • splitHonorQuotes

        @NotNull
        public static java.util.List<java.lang.String> splitHonorQuotes​(@NotNull
                                                                        java.lang.String s)
      • stringValueOf

        @NotNull
        public static java.lang.String stringValueOf​(@Nullable
                                                     java.lang.Object obj,
                                                     @NotNull
                                                     java.lang.String defaultValue)
      • collapseSpaces

        public static java.lang.String collapseSpaces​(@NotNull
                                                      java.lang.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 java.lang.String replaceNewLines​(@NotNull
                                                       java.lang.String str,
                                                       @NotNull
                                                       java.lang.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 java.lang.String newLineToSpaceDelimited​(@NotNull
                                                               java.lang.String str)
        Parameters:
        str - string to transform
        Returns:
        replaces sequences of new lines with single space. Resulted string is trimmed.
        Since:
        7.0
      • removeNonBMPCharacters

        @NotNull
        public static java.lang.String removeNonBMPCharacters​(@NotNull
                                                              java.lang.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
                                                  java.lang.String str)
      • escapeDataForCSV

        public static void escapeDataForCSV​(@NotNull
                                            java.io.Writer writer,
                                            java.lang.String... data)
      • escapeForCSV

        public static java.lang.String escapeForCSV​(@NotNull
                                                    java.lang.String... data)
      • objectToString

        @Nullable
        @Contract("null -> null")
        public static java.lang.String objectToString​(@Nullable
                                                      java.lang.Object object)
        Safely calls Object.toString().
        Parameters:
        object - object
        Returns:
        return result of object toString() if object is not null or returns null
      • splitLines

        @NotNull
        public static java.lang.String[] splitLines​(@NotNull
                                                    java.lang.String string)
        Splits the string by lines. Does not remove any leading/trailing spaces.
        See Also:
        StringUtil.splitByLines(String)