Verified Owner
Top Fields Constructors Methods
org.jabref.logic.util.strings

public Class StringUtil

extends Object
Class Inheritance
Annotations
@SuppressWarnings:checkstyle:NoMultipleClosingBracesAtEndOfLine
@AllowedToUseApacheCommonsLang3:There is no equivalent in Google\'s Guava
@AllowedToUseLogic:OS.NewLine is most basic
Imports
java.text.Normalizer, java.util.ArrayList, .Arrays, .List, .Locale, .Map, .Objects, .Optional, java.util.regex.Matcher, .Pattern, javafx.util.Pair, org.jabref.architecture.AllowedToUseApacheCommonsLang3, .AllowedToUseLogic, org.jabref.logic.bibtex.FieldWriter, org.jabref.logic.os.OS, org.jabref.model.strings.UnicodeToReadableCharMap, com.google.common.base.CharMatcher, org.apache.commons.lang3.StringUtils, .Strings, org.jspecify.annotations.NonNull, .Nullable

Field Summary

Modifier and TypeField and Description
private static final Pattern
private static final Pattern
private static final Pattern
NORMALIZE_PATTERN

Pattern for normalizing whitespace and punctuation using named capture groups

public static final String
private static final Pattern
private static final String
private static final UnicodeToReadableCharMap
private static final String

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
private static void
addWrappedLine(StringBuilder result, String
the line of text to be wrapped and appended
line
,
int
the number of characters belonging to a line of text
wrapAmount
,
String
a string containing the newline character(s)
newlineString
)

Appends a text to a string builder.

public static String
public static String
boldHTML(String input)

Return string enclosed in HTML bold tags

public static String
boldHTML(String input, String alternative)

Return string enclosed in HTML bold tags if not null, otherwise return alternative text in HTML bold tags

public static String
booleanToBinaryString(boolean expression)

public static String
capitalizeFirst(String toCapitalize)

Make first character of String uppercase, and the rest lowercase.

public static boolean
containsIgnoreCase(String text, String searchString)

public static boolean

Returns:

True if the given string does contain at least one whitespace character, False otherwise
containsWhitespace
(String
The string to check
s
)

Checks if the given string contains any whitespace characters.

public static String[][]

Returns:

The decoded String array.
decodeStringDoubleArray
(String
The encoded String to be decoded.
value
)

Decodes an encoded double String array back into array form.

public static boolean
public static boolean
public static String
getCorrectFileName(String orgName, String defaultExtension)

extends the filename with a default Extension, if no Extension '.x' could be found

public static String
getPart(String text, int startIndex, boolean terminateOnEndBraceOnly)

Creates a substring from a text

public static List<String>
getStringAsSentences(String text)

Returns a list of sentences contained in the given text.

public static List<String>

Returns:

a list of words
getStringAsWords
(String
the input
text
)

Returns a list of words contained in the given text.

public static String
public static int

Returns:

the int value of str
intValueOf
(String
the String holding an Integer value
str
)

Optimized method for converting a String into an Integer

From http://stackoverflow.com/questions/1030479/most-efficient-way-of-converting-string-to-integer-in-java

public static Optional<Integer>

Returns:

the int value of str or Optional.empty() if not possible
intValueOfOptional
(String
the String holding an Integer value
str
)

Optimized method for converting a String into an Integer

From http://stackoverflow.com/questions/1030479/most-efficient-way-of-converting-string-to-integer-in-java

public static boolean
public static boolean
public static boolean
public static boolean

Returns:

True, if the check was successful. False otherwise.
isInCurlyBrackets
(String
The string to check
toCheck
)

Checks if the given String has exactly one pair of surrounding curly braces

Strings with escaped characters in curly braces at the beginning and end are respected, too

public static boolean
public static boolean
isNotBlank(@Nullable String string)

Checks if a CharSequence is not empty (""), not null and not whitespace only.

public static boolean
public static boolean
public static String
join(String[] strings, String separator, int from, int
Excluding stringsto
to
)

Concatenate all strings in the array from index 'from' to 'to' (excluding to) with the given separator.

public static String
limitStringLength(String s, int
the maximum length of the string - <= 0 means no limit
maxLength
)

Limits the length of a string to a maximum length.

public static String
public static String

Returns:

The resulting string after wrapping capitals.
putBracesAroundCapitals
(String
The string to modify.
s
)

Wrap all uppercase letters, or sequences of uppercase letters, in curly braces.

public static String

Returns:

A String with every special character (including the quoting character itself) quoted.
quote
(String
The String which may contain special characters.
toQuote
,
String
A String containing all special characters except the quoting character itself, which is automatically quoted.
specials
,
char
The quoting character.
quoteChar
)

Quote special characters.

public static String
quoteForHTML(String toQuote)

Quotes each and every character, e.g. '!' as !.

public static String

Returns:

Returns a string
quoteStringIfSpaceIsContained
(String string)

Encloses the given string with " if there is a space contained

public static String

Returns:

A new String with braces removed.
removeBracesAroundCapitals
(String
The String to analyze.
s
)

This method looks for occurrences of capital letters enclosed in an arbitrary number of pairs of braces, e.g. "{AB}" or "{{T}}".

private static String

Returns:

A new String with braces removed.
removeSingleBracesAroundCapitals
(String
The String to analyze.
s
)

This method looks for occurrences of capital letters enclosed in one pair of braces, e.g. "{AB}".

public static String
removeStringAtTheEnd(String string, String stringToBeRemoved)

public static String
replaceSpecialCharacters(String s)

Replace non-English characters like umlauts etc. with a sensible letter or letter combination that bibtex can accept.

public static String
shaveString(String toShave)

Returns the string, after shaving off whitespace at the beginning and end, and removing (at most) one pair of braces or " surrounding it.

public static ArrayList<String>

Returns:

a list of tokens
splitRespectingEscapedWhitespace
(String
the string to split
path
)

Splits a string by whitespace, treating backslash-escaped spaces as part of the same token.

public static String
stripAccents(String searchQuery)

public static String
stripBrackets(String toStrip)

Removes optional square brackets from the string s

public static String

Returns:

The in String, stripped of non-valid characters.
stripNonValidXMLCharacters
(String
The String whose non-valid characters we want to remove.
in
)

This method ensures that the output String has only valid XML unicode characters as specified by the XML 1.0 standard.

public static String
public static List<String>
tokenizeToList(String
String to be tokenized
buffer
,
String
Delimiter string
delimiter
)

Returns: list java.util.List of String

public static String

Returns:

a String with only OS.NEWLINE as line breaks
unifyLineBreaks
(String s, String newline)

Replaces all platform-dependent line breaks by OS.NEWLINE line breaks.

public static String

Returns:

A String with all quoted characters unquoted.
unquote
(String
The String which may contain quoted special characters.
toUnquote
,
char
The quoting character.
quoteChar
)

Unquote special characters.

public static String

Returns:

the wrapped string
wrap
(String
the string to wrap
in
,
int
the number of characters belonging to a line of text
wrapAmount
,
String
the newline character(s)
newline
)

Formats field contents for output.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

BRACED_TITLE_CAPITAL_PATTERNback to summary
private static final Pattern BRACED_TITLE_CAPITAL_PATTERN
LINE_BREAKSback to summary
private static final Pattern LINE_BREAKS
NORMALIZE_PATTERNback to summary
private static final Pattern NORMALIZE_PATTERN

Pattern for normalizing whitespace and punctuation using named capture groups

SPECIAL_COMMAND_CHARSback to summary
public static final String SPECIAL_COMMAND_CHARS
SPLIT_TEXT_PATTERNback to summary
private static final Pattern SPLIT_TEXT_PATTERN
STRING_TABLE_DELIMITERback to summary
private static final String STRING_TABLE_DELIMITER
UNICODE_CHAR_MAPback to summary
private static final UnicodeToReadableCharMap UNICODE_CHAR_MAP
WRAPPED_LINE_PREFIXback to summary
private static final String WRAPPED_LINE_PREFIX

Constructor Detail

StringUtilback to summary
public StringUtil()

Method Detail

addWrappedLineback to summary
private static void addWrappedLine(StringBuilder result, String line, int wrapAmount, String newlineString)

Appends a text to a string builder. Wraps the text so that each line is approx wrapAmount characters long. Wrapping is done using newline and tab character.

Parameters
line:String

the line of text to be wrapped and appended

wrapAmount:int

the number of characters belonging to a line of text

newlineString:String

a string containing the newline character(s)

alignStringTableback to summary
public static String alignStringTable(List<Pair<String, String>> table)
boldHTMLback to summary
public static String boldHTML(String input)

Return string enclosed in HTML bold tags

boldHTMLback to summary
public static String boldHTML(String input, String alternative)

Return string enclosed in HTML bold tags if not null, otherwise return alternative text in HTML bold tags

booleanToBinaryStringback to summary
public static String booleanToBinaryString(boolean expression)
capitalizeFirstback to summary
public static String capitalizeFirst(String toCapitalize)

Make first character of String uppercase, and the rest lowercase.

containsIgnoreCaseback to summary
public static boolean containsIgnoreCase(String text, String searchString)
Annotations
@AllowedToUseApacheCommonsLang3:No direct Guava equivalent existing - see https://stackoverflow.com/q/16560635/873282
containsWhitespaceback to summary
public static boolean containsWhitespace(String s)

Checks if the given string contains any whitespace characters. The supported whitespace characters are the set of characters matched by \s in regular expressions, which are [ \t\n\x0B\f\r].

Parameters
s:String

The string to check

Returns:boolean

True if the given string does contain at least one whitespace character, False otherwise

decodeStringDoubleArrayback to summary
public static String[][] decodeStringDoubleArray(String value)

Decodes an encoded double String array back into array form. The array is assumed to be square, and delimited by the characters ';' (first dim) and ':' (second dim).

Parameters
value:String

The encoded String to be decoded.

Returns:String[][]

The decoded String array.

endsWithIgnoreCaseback to summary
public static boolean endsWithIgnoreCase(String string, String suffix)
Annotations
@AllowedToUseApacheCommonsLang3:No Guava equivalent existing
equalsUnifiedLineBreakback to summary
public static boolean equalsUnifiedLineBreak(Optional<String> stringOne, Optional<String> stringTwo)
getCorrectFileNameback to summary
public static String getCorrectFileName(String orgName, String defaultExtension)

extends the filename with a default Extension, if no Extension '.x' could be found

getPartback to summary
public static String getPart(String text, int startIndex, boolean terminateOnEndBraceOnly)

Creates a substring from a text

getStringAsSentencesback to summary
public static List<String> getStringAsSentences(String text)

Returns a list of sentences contained in the given text.

getStringAsWordsback to summary
public static List<String> getStringAsWords(String text)

Returns a list of words contained in the given text. Whitespace, comma and semicolon are considered as separator between words.

Parameters
text:String

the input

Returns:List<String>

a list of words

ignoreCurlyBracketback to summary
public static String ignoreCurlyBracket(String title)
intValueOfback to summary
public static int intValueOf(String str)

Optimized method for converting a String into an Integer

From http://stackoverflow.com/questions/1030479/most-efficient-way-of-converting-string-to-integer-in-java

Parameters
str:String

the String holding an Integer value

Returns:int

the int value of str

Exceptions
NumberFormatException:
if str cannot be parsed to an int
intValueOfOptionalback to summary
public static Optional<Integer> intValueOfOptional(String str)

Optimized method for converting a String into an Integer

From http://stackoverflow.com/questions/1030479/most-efficient-way-of-converting-string-to-integer-in-java

Parameters
str:String

the String holding an Integer value

Returns:Optional<Integer>

the int value of str or Optional.empty() if not possible

isBlankback to summary
public static boolean isBlank(@Nullable String string)
isBlankback to summary
public static boolean isBlank(@NonNull Optional<String> string)
isInCitationMarksback to summary
public static boolean isInCitationMarks(String toCheck)
isInCurlyBracketsback to summary
public static boolean isInCurlyBrackets(String toCheck)

Checks if the given String has exactly one pair of surrounding curly braces

Strings with escaped characters in curly braces at the beginning and end are respected, too

Parameters
toCheck:String

The string to check

Returns:boolean

True, if the check was successful. False otherwise.

isInSquareBracketsback to summary
public static boolean isInSquareBrackets(String toCheck)
isNotBlankback to summary
public static boolean isNotBlank(@Nullable String string)

Checks if a CharSequence is not empty (""), not null and not whitespace only.

isNotBlankback to summary
public static boolean isNotBlank(Optional<String> string)
isNullOrEmptyback to summary
public static boolean isNullOrEmpty(@Nullable String toTest)
joinback to summary
public static String join(String[] strings, String separator, int from, int to)

Concatenate all strings in the array from index 'from' to 'to' (excluding to) with the given separator.

Example:

String[] s = "ab/cd/ed".split("/"); join(s, "\", 0, s.length) -> "ab\cd\ed"

Parameters
to:int

Excluding stringsto

limitStringLengthback to summary
public static String limitStringLength(String s, int maxLength)

Limits the length of a string to a maximum length.

Note the implementation is different from StringUtils.substring, because it accepts parameters smaller than 4.

Parameters
maxLength:int

the maximum length of the string - <= 0 means no limit

makeSafeback to summary
public static String makeSafe(@Nullable String string)
putBracesAroundCapitalsback to summary
public static String putBracesAroundCapitals(String s)

Wrap all uppercase letters, or sequences of uppercase letters, in curly braces. Ignore letters within a pair of # character, as these are part of a string label that should not be modified.

Parameters
s:String

The string to modify.

Returns:String

The resulting string after wrapping capitals.

quoteback to summary
public static String quote(String toQuote, String specials, char quoteChar)

Quote special characters.

Parameters
toQuote:String

The String which may contain special characters.

specials:String

A String containing all special characters except the quoting character itself, which is automatically quoted.

quoteChar:char

The quoting character.

Returns:String

A String with every special character (including the quoting character itself) quoted.

quoteForHTMLback to summary
public static String quoteForHTML(String toQuote)

Quotes each and every character, e.g. '!' as !. Used for verbatim display of arbitrary strings that may contain HTML entities.

quoteStringIfSpaceIsContainedback to summary
public static String quoteStringIfSpaceIsContained(String string)

Encloses the given string with " if there is a space contained

Returns:String

Returns a string

removeBracesAroundCapitalsback to summary
public static String removeBracesAroundCapitals(String s)

This method looks for occurrences of capital letters enclosed in an arbitrary number of pairs of braces, e.g. "{AB}" or "{{T}}". All of these pairs of braces are removed.

Parameters
s:String

The String to analyze.

Returns:String

A new String with braces removed.

removeSingleBracesAroundCapitalsback to summary
private static String removeSingleBracesAroundCapitals(String s)

This method looks for occurrences of capital letters enclosed in one pair of braces, e.g. "{AB}". All these are replaced by only the capitals in between the braces.

Parameters
s:String

The String to analyze.

Returns:String

A new String with braces removed.

removeStringAtTheEndback to summary
public static String removeStringAtTheEnd(String string, String stringToBeRemoved)
Annotations
@AllowedToUseApacheCommonsLang3:No Guava equivalent existing - see https://stackoverflow.com/a/23825984
replaceSpecialCharactersback to summary
public static String replaceSpecialCharacters(String s)

Replace non-English characters like umlauts etc. with a sensible letter or letter combination that bibtex can accept. The basis for replacement is the HashMap UnicodeToReadableCharMap.

shaveStringback to summary
public static String shaveString(String toShave)

Returns the string, after shaving off whitespace at the beginning and end, and removing (at most) one pair of braces or " surrounding it.

splitRespectingEscapedWhitespaceback to summary
public static ArrayList<String> splitRespectingEscapedWhitespace(String path)

Splits a string by whitespace, treating backslash-escaped spaces as part of the same token.

Example: ""C:\Current Python\python.exe" -m ocrmypdf" -> [""C:\Current Python\python.exe"", "-m", "ocrmypdf"]

Parameters
path:String

the string to split

Returns:ArrayList<String>

a list of tokens

stripAccentsback to summary
public static String stripAccents(String searchQuery)
Annotations
@AllowedToUseApacheCommonsLang3:No Guava equivalent existing - see https://stackoverflow.com/q/3322152/873282 for a list of other implementations
stripBracketsback to summary
public static String stripBrackets(String toStrip)

Removes optional square brackets from the string s

stripNonValidXMLCharactersback to summary
public static String stripNonValidXMLCharacters(String in)

This method ensures that the output String has only valid XML unicode characters as specified by the XML 1.0 standard. For reference, please see the standard. This method will return an empty String if the input is null or empty.

URL: http://cse-mjmcl.cse.bris.ac.uk/blog/2007/02/14/1171465494443.html

Parameters
in:String

The String whose non-valid characters we want to remove.

Returns:String

The in String, stripped of non-valid characters.

substringBetweenback to summary
public static String substringBetween(String str, String open, String close)
tokenizeToListback to summary
public static List<String> tokenizeToList(String buffer, String delimiter)
Parameters
buffer:String

String to be tokenized

delimiter:String

Delimiter string

Returns:List<String>

list java.util.List of String

unifyLineBreaksback to summary
public static String unifyLineBreaks(String s, String newline)

Replaces all platform-dependent line breaks by OS.NEWLINE line breaks. AKA normalize newlines

We do NOT use UNIX line breaks as the user explicitly configures its linebreaks and this method is used in bibtex field writing

Example

```text Legacy Macintosh \r -> OS.NEWLINE Windows \r\n -> OS.NEWLINE ```
Returns:String

a String with only OS.NEWLINE as line breaks

unquoteback to summary
public static String unquote(String toUnquote, char quoteChar)

Unquote special characters.

Parameters
toUnquote:String

The String which may contain quoted special characters.

quoteChar:char

The quoting character.

Returns:String

A String with all quoted characters unquoted.

wrapback to summary
public static String wrap(String in, int wrapAmount, String newline)

Formats field contents for output. Must be "symmetric" with the parse method above, so stored and reloaded fields are not mangled.

Parameters
in:String

the string to wrap

wrapAmount:int

the number of characters belonging to a line of text

newline:String

the newline character(s)

Returns:String

the wrapped string