Class StringUtil
- java.lang.Object
-
- freemarker.template.utility.StringUtil
-
public class StringUtil extends java.lang.Object
Some text related utilities.
-
-
Constructor Summary
Constructors Constructor Description StringUtil()
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static java.lang.String
capitalize(java.lang.String s)
static java.lang.String
chomp(java.lang.String s)
Removes a line-break from the end of the string (if there's any).static java.util.Locale
deduceLocale(java.lang.String input)
static java.lang.String
emptyToNull(java.lang.String s)
Converts a 0-length string to null, leaves the string as is otherwise.static java.lang.String
ftlQuote(java.lang.String s)
Creates a quoted FTL string literal from a string, using escaping where necessary.static java.lang.String
FTLStringLiteralDec(java.lang.String s)
FTL string literal decoding.static java.lang.String
FTLStringLiteralEnc(java.lang.String s)
Escapes a string according the FTL string literal escaping rules; it doesn't add the quotation marks.static java.lang.String
FTLStringLiteralEnc(java.lang.String s, char quotation)
Escapes a string according the FTL string literal escaping rules, assuming the literal is quoted withquotation
; it doesn't add the quotation marks itself.static boolean
getYesNo(java.lang.String s)
static java.util.regex.Pattern
globToRegularExpression(java.lang.String glob)
static java.util.regex.Pattern
globToRegularExpression(java.lang.String glob, boolean caseInsensitive)
Creates a regular expression from a glob.static java.lang.String
HTMLEnc(java.lang.String s)
Deprecated.UseXHTMLEnc(String)
instead, because it escapes apostrophe-quote too.static boolean
isBackslashEscapedFTLIdentifierCharacter(char c)
Tells if a character can occur in an FTL identifier if it's preceded with a backslash.static boolean
isFTLIdentifierPart(char c)
Tells if a character can occur in an FTL identifier expression (without escaping) as other than the first character.static boolean
isFTLIdentifierStart(char c)
Tells if a character can occur on the beginning of an FTL identifier expression (without escaping).static boolean
isTrimmableToEmpty(char[] text)
Tells ifString.trim()
will return a 0-length string for theString
equivalent of the argument.static boolean
isTrimmableToEmpty(char[] text, int start)
LikeisTrimmableToEmpty(char[])
, but acts on a sub-array that starts atstart
(inclusive index).static boolean
isTrimmableToEmpty(char[] text, int start, int end)
LikeisTrimmableToEmpty(char[])
, but acts on a sub-array that starts atstart
(inclusive index) and ends atend
(exclusive index).static boolean
isXMLID(java.lang.String name)
Deprecated.Don't use this outside FreeMarker; it's name if misleading, and it doesn't follow the XML specs.static java.lang.String
javaScriptStringEnc(java.lang.String s)
Escapes aString
to be safely insertable into a JavaScript string literal; for more seejsStringEnc(s, false)
.static java.lang.String
javaStringEnc(java.lang.String s)
Escapes theString
with the escaping rules of Java language string literals, so it's safe to insert the value into a string literal.static java.lang.String
jQuote(java.lang.Object obj)
static java.lang.String
jQuote(java.lang.String s)
Quotes string as Java Language string literal.static java.lang.String
jQuoteNoXSS(java.lang.Object obj)
static java.lang.String
jQuoteNoXSS(java.lang.String s)
static java.lang.String
jsonStringEnc(java.lang.String s)
Escapes aString
to be safely insertable into a JSON string literal; for more seejsStringEnc(s, true)
.static java.lang.String
jsStringEnc(java.lang.String s, boolean json)
Escapes aString
to be safely insertable into a JavaScript or a JSON string literal.static java.lang.String
leftPad(java.lang.String s, int minLength)
Pads the string at the left with spaces until it reaches the desired length.static java.lang.String
leftPad(java.lang.String s, int minLength, char filling)
Pads the string at the left with the specified character until it reaches the desired length.static java.lang.String
leftPad(java.lang.String s, int minLength, java.lang.String filling)
Pads the string at the left with a filling pattern until it reaches the desired length.static boolean
matchesName(java.lang.String qname, java.lang.String nodeName, java.lang.String nsURI, Environment env)
static java.util.Map
parseNameValuePairList(java.lang.String s, java.lang.String defaultValue)
Parses a name-value pair list, where the pairs are separated with comma, and the name and value is separated with colon.static java.lang.String
replace(java.lang.String text, java.lang.String oldSub, java.lang.String newSub)
Same asreplace(String, String, String, boolean, boolean)
with twofalse
parameters.static java.lang.String
replace(java.lang.String text, java.lang.String oldsub, java.lang.String newsub, boolean caseInsensitive, boolean firstOnly)
Replaces all occurrences of a sub-string in a string.static java.lang.String
rightPad(java.lang.String s, int minLength)
Pads the string at the right with spaces until it reaches the desired length.static java.lang.String
rightPad(java.lang.String s, int minLength, char filling)
Pads the string at the right with the specified character until it reaches the desired length.static java.lang.String
rightPad(java.lang.String s, int minLength, java.lang.String filling)
Pads the string at the right with a filling pattern until it reaches the desired length.static java.lang.String
RTFEnc(java.lang.String s)
Rich Text Format encoding (does not replace line breaks).static void
RTFEnc(java.lang.String s, java.io.Writer out)
LikeRTFEnc(String)
, but writes the result into aWriter
.static java.lang.String[]
split(java.lang.String s, char c)
Splits a string at the specified character.static java.lang.String[]
split(java.lang.String s, java.lang.String sep, boolean caseInsensitive)
Splits a string at the specified string.static java.lang.String
toLowerABC(int n)
Same astoUpperABC(int)
, but produces lower case result, like"ab"
.static java.lang.String
toUpperABC(int n)
Converts1
,2
,3
and so forth to"A"
,"B"
,"C"
and so fort.static char[]
trim(char[] cs)
Behaves exactly likeString.trim()
, but works on arrays.static java.lang.String
tryToString(java.lang.Object object)
Tries to runtoString()
, but if that fails, returns a"[com.example.SomeClass.toString() failed: " + e + "]"
instead.static java.lang.String
URLEnc(java.lang.String s, java.lang.String charset)
URL encoding (like%20this) for query parameter values, path segments, fragments; this encodes all characters that are reserved anywhere.static java.lang.String
URLPathEnc(java.lang.String s, java.lang.String charset)
LikeURLEnc(String, String)
but doesn't escape the slash character (/
).static int
versionStringToInt(java.lang.String version)
Converts a version number string to an integer for easy comparison.static java.lang.String
XHTMLEnc(java.lang.String s)
XHTML Encoding.static void
XHTMLEnc(java.lang.String s, java.io.Writer out)
LikeXHTMLEnc(String)
, but writes the result into aWriter
.static java.lang.String
XMLEnc(java.lang.String s)
XML Encoding.static void
XMLEnc(java.lang.String s, java.io.Writer out)
LikeXMLEnc(String)
, but writes the result into aWriter
.static java.lang.String
XMLEncNA(java.lang.String s)
XML encoding without replacing apostrophes.static java.lang.String
XMLEncNQG(java.lang.String s)
XML encoding without replacing apostrophes and quotation marks and greater-thans (except in]]>
).static java.lang.String
XMLEncQAttr(java.lang.String s)
XML encoding for attribute values quoted with " (not with '!).
-
-
-
Method Detail
-
HTMLEnc
@Deprecated public static java.lang.String HTMLEnc(java.lang.String s)
Deprecated.UseXHTMLEnc(String)
instead, because it escapes apostrophe-quote too.HTML encoding (does not convert line breaks and apostrophe-quote). Replaces all '>' '<' '&' and '"' with entity reference, but not "'" (apostrophe-quote). The last is not escaped as back then when this was written some user agents didn't understood "'" nor "'".
-
XMLEnc
public static java.lang.String XMLEnc(java.lang.String s)
XML Encoding. Replaces all '>' '<' '&', "'" and '"' with entity reference
-
XMLEnc
public static void XMLEnc(java.lang.String s, java.io.Writer out) throws java.io.IOException
LikeXMLEnc(String)
, but writes the result into aWriter
.- Throws:
java.io.IOException
- Since:
- 2.3.24
-
XHTMLEnc
public static java.lang.String XHTMLEnc(java.lang.String s)
XHTML Encoding. Replaces all '>' '<' '&', "'" and '"' with entity reference suitable for XHTML decoding in common user agents (including legacy user agents, which do not decode "'" to "'", so "'" is used instead [see http://www.w3.org/TR/xhtml1/#C_16])
-
XHTMLEnc
public static void XHTMLEnc(java.lang.String s, java.io.Writer out) throws java.io.IOException
LikeXHTMLEnc(String)
, but writes the result into aWriter
.- Throws:
java.io.IOException
- Since:
- 2.3.24
-
XMLEncNA
public static java.lang.String XMLEncNA(java.lang.String s)
XML encoding without replacing apostrophes.- See Also:
XMLEnc(String)
-
XMLEncQAttr
public static java.lang.String XMLEncQAttr(java.lang.String s)
XML encoding for attribute values quoted with " (not with '!). Also can be used for HTML attributes that are quoted with ".- See Also:
XMLEnc(String)
-
XMLEncNQG
public static java.lang.String XMLEncNQG(java.lang.String s)
XML encoding without replacing apostrophes and quotation marks and greater-thans (except in]]>
).- See Also:
XMLEnc(String)
-
RTFEnc
public static java.lang.String RTFEnc(java.lang.String s)
Rich Text Format encoding (does not replace line breaks). Escapes all '\' '{' '}'.
-
RTFEnc
public static void RTFEnc(java.lang.String s, java.io.Writer out) throws java.io.IOException
LikeRTFEnc(String)
, but writes the result into aWriter
.- Throws:
java.io.IOException
- Since:
- 2.3.24
-
URLEnc
public static java.lang.String URLEnc(java.lang.String s, java.lang.String charset) throws java.io.UnsupportedEncodingException
URL encoding (like%20this) for query parameter values, path segments, fragments; this encodes all characters that are reserved anywhere.- Throws:
java.io.UnsupportedEncodingException
-
URLPathEnc
public static java.lang.String URLPathEnc(java.lang.String s, java.lang.String charset) throws java.io.UnsupportedEncodingException
LikeURLEnc(String, String)
but doesn't escape the slash character (/
). This can be used to encode a path only if you know that no folder or file name will contain/
character (not in the path, but in the name itself), which usually stands, as the commonly used OS-es don't allow that.- Throws:
java.io.UnsupportedEncodingException
- Since:
- 2.3.21
-
FTLStringLiteralEnc
public static java.lang.String FTLStringLiteralEnc(java.lang.String s, char quotation)
Escapes a string according the FTL string literal escaping rules, assuming the literal is quoted withquotation
; it doesn't add the quotation marks itself.- Parameters:
quotation
- Either'"'
or'\''
. It's assumed that the string literal whose part we calculate is enclosed within this kind of quotation mark. Thus, the other kind of quotation character will not be escaped in the result.- Since:
- 2.3.22
-
FTLStringLiteralEnc
public static java.lang.String FTLStringLiteralEnc(java.lang.String s)
Escapes a string according the FTL string literal escaping rules; it doesn't add the quotation marks. As this method doesn't know if the string literal is quoted with reuglar quotation marks or apostrophe quute, it will escape both.- See Also:
FTLStringLiteralEnc(String, char)
-
FTLStringLiteralDec
public static java.lang.String FTLStringLiteralDec(java.lang.String s) throws ParseException
FTL string literal decoding. \\, \", \', \n, \t, \r, \b and \f will be replaced according to Java rules. In additional, it knows \g, \l, \a and \{ which are replaced with <, >, & and { respectively. \x works as hexadecimal character code escape. The character codes are interpreted according to UCS basic plane (Unicode). "f\x006Fo", "f\x06Fo" and "f\x6Fo" will be "foo". "f\x006F123" will be "foo123" as the maximum number of digits is 4. All other \X (where X is any character not mentioned above or End-of-string) will cause a ParseException.- Parameters:
s
- String literal without the surrounding quotation marks- Returns:
- String with all escape sequences resolved
- Throws:
ParseException
- if there string contains illegal escapes
-
deduceLocale
public static java.util.Locale deduceLocale(java.lang.String input)
-
capitalize
public static java.lang.String capitalize(java.lang.String s)
-
getYesNo
public static boolean getYesNo(java.lang.String s)
-
split
public static java.lang.String[] split(java.lang.String s, char c)
Splits a string at the specified character.
-
split
public static java.lang.String[] split(java.lang.String s, java.lang.String sep, boolean caseInsensitive)
Splits a string at the specified string.- Parameters:
sep
- The string that separates the items of the resulting array. Since 2.3.28, if this is 0 length, then each character will be a separate item in the array.
-
replace
public static java.lang.String replace(java.lang.String text, java.lang.String oldSub, java.lang.String newSub)
Same asreplace(String, String, String, boolean, boolean)
with twofalse
parameters.- Since:
- 2.3.20
-
replace
public static java.lang.String replace(java.lang.String text, java.lang.String oldsub, java.lang.String newsub, boolean caseInsensitive, boolean firstOnly)
Replaces all occurrences of a sub-string in a string.- Parameters:
text
- The string where it will replaceoldsub
withnewsub
.- Returns:
- String The string after the replacements.
-
chomp
public static java.lang.String chomp(java.lang.String s)
Removes a line-break from the end of the string (if there's any).
-
emptyToNull
public static java.lang.String emptyToNull(java.lang.String s)
Converts a 0-length string to null, leaves the string as is otherwise.- Parameters:
s
- maybenull
.
-
jQuote
public static java.lang.String jQuote(java.lang.Object obj)
-
jQuote
public static java.lang.String jQuote(java.lang.String s)
Quotes string as Java Language string literal. Returns string"null"
ifs
isnull
.
-
jQuoteNoXSS
public static java.lang.String jQuoteNoXSS(java.lang.Object obj)
-
jQuoteNoXSS
public static java.lang.String jQuoteNoXSS(java.lang.String s)
Same asjQuoteNoXSS(String)
but also escapes'<'
as\
u003C
. This is used for log messages to prevent XSS on poorly written Web-based log viewers.
-
ftlQuote
public static java.lang.String ftlQuote(java.lang.String s)
Creates a quoted FTL string literal from a string, using escaping where necessary. The result either uses regular quotation marks (UCS 0x22) or apostrophe-quotes (UCS 0x27), depending on the string content. (Currently, apostrophe-quotes will be chosen exactly when the string contains regular quotation character and doesn't contain apostrophe-quote character.)- Parameters:
s
- The value that should be converted to an FTL string literal whose evaluated value equals tos
- Since:
- 2.3.22
-
isFTLIdentifierStart
public static boolean isFTLIdentifierStart(char c)
Tells if a character can occur on the beginning of an FTL identifier expression (without escaping).- Since:
- 2.3.22
-
isFTLIdentifierPart
public static boolean isFTLIdentifierPart(char c)
Tells if a character can occur in an FTL identifier expression (without escaping) as other than the first character.- Since:
- 2.3.22
-
isBackslashEscapedFTLIdentifierCharacter
public static boolean isBackslashEscapedFTLIdentifierCharacter(char c)
Tells if a character can occur in an FTL identifier if it's preceded with a backslash. For example,"-"
is a such character (as you can have an identifier likefoo\-bar
in FTL), but"f"
is not, as it needn't be, and can't be escaped.- Since:
- 2.3.31
-
javaStringEnc
public static java.lang.String javaStringEnc(java.lang.String s)
Escapes theString
with the escaping rules of Java language string literals, so it's safe to insert the value into a string literal. The resulting string will not be quoted.All characters under UCS code point 0x20 will be escaped. Where they have no dedicated escape sequence in Java, they will be replaced with hexadecimal escape (\uXXXX).
- See Also:
jQuote(String)
-
javaScriptStringEnc
public static java.lang.String javaScriptStringEnc(java.lang.String s)
Escapes aString
to be safely insertable into a JavaScript string literal; for more seejsStringEnc(s, false)
.
-
jsonStringEnc
public static java.lang.String jsonStringEnc(java.lang.String s)
Escapes aString
to be safely insertable into a JSON string literal; for more seejsStringEnc(s, true)
.
-
jsStringEnc
public static java.lang.String jsStringEnc(java.lang.String s, boolean json)
Escapes aString
to be safely insertable into a JavaScript or a JSON string literal. The resulting string will not be quoted; the caller must ensure that they are there in the final output. Note that for JSON, the quotation marks must be"
, not'
, because JSON doesn't escape'
.The escaping rules guarantee that if the inside of the JavaScript/JSON string literal is from one or more touching pieces that were escaped with this, no character sequence can occur that closes the JavaScript/JSON string literal, or has a meaning in HTML/XML that causes the HTML script section to be closed. (If, however, the escaped section is preceded by or followed by strings from other sources, this can't be guaranteed in some rare cases. Like x = "</${a?js_string}" might closes the "script" element if
a
is"script>"
.) The escaped characters are:Input Output " \" ' if not in JSON-mode \' \ \\ / if the method can't know that it won't be directly after < \/ > if the method can't know that it won't be directly after ]] or -- JavaScript: \>; JSON: \u003E < if the method can't know that it won't be directly followed by ! or ? \u003C u0000-u001f (UNICODE control characters - disallowed by JSON)
u007f-u009f (UNICODE control characters - disallowed by JSON)\n, \r and such, or if there's no such dedicated escape: JavaScript: \xXX, JSON: \uXXXX u2028 (Line separator - source code line-break in ECMAScript)
u2029 (Paragraph separator - source code line-break in ECMAScript)
\uXXXX - Since:
- 2.3.20
-
parseNameValuePairList
public static java.util.Map parseNameValuePairList(java.lang.String s, java.lang.String defaultValue) throws java.text.ParseException
Parses a name-value pair list, where the pairs are separated with comma, and the name and value is separated with colon. The keys and values can contain only letters, digits and _. They can't be quoted. White-space around the keys and values are ignored. The value can be omitted ifdefaultValue
is not null. When a value is omitted, then the colon after the key must be omitted as well. The same key can't be used for multiple times.- Parameters:
s
- the string to parse. For example:"strong:100, soft:900"
.defaultValue
- the value used when the value is omitted in a key-value pair.- Returns:
- the map that contains the name-value pairs.
- Throws:
java.text.ParseException
- if the string is not a valid name-value pair list.
-
isXMLID
@Deprecated public static boolean isXMLID(java.lang.String name)
Deprecated.Don't use this outside FreeMarker; it's name if misleading, and it doesn't follow the XML specs.Used internally by the XML DOM wrapper to check if the subvariable name is just an element name, or a more complex XPath expression.- Returns:
- whether the name is a valid XML element name. (This routine might only be 99% accurate. REVISIT)
-
matchesName
public static boolean matchesName(java.lang.String qname, java.lang.String nodeName, java.lang.String nsURI, Environment env)
- Returns:
- whether the qname matches the combination of nodeName, nsURI, and environment prefix settings.
-
leftPad
public static java.lang.String leftPad(java.lang.String s, int minLength)
Pads the string at the left with spaces until it reaches the desired length. If the string is longer than this length, then it returns the unchanged string.- Parameters:
s
- the string that will be padded.minLength
- the length to reach.
-
leftPad
public static java.lang.String leftPad(java.lang.String s, int minLength, char filling)
Pads the string at the left with the specified character until it reaches the desired length. If the string is longer than this length, then it returns the unchanged string.- Parameters:
s
- the string that will be padded.minLength
- the length to reach.filling
- the filling pattern.
-
leftPad
public static java.lang.String leftPad(java.lang.String s, int minLength, java.lang.String filling)
Pads the string at the left with a filling pattern until it reaches the desired length. If the string is longer than this length, then it returns the unchanged string. For example:leftPad('ABC', 9, '1234')
returns"123412ABC"
.- Parameters:
s
- the string that will be padded.minLength
- the length to reach.filling
- the filling pattern. Must be at least 1 characters long. Can't benull
.
-
rightPad
public static java.lang.String rightPad(java.lang.String s, int minLength)
Pads the string at the right with spaces until it reaches the desired length. If the string is longer than this length, then it returns the unchanged string.- Parameters:
s
- the string that will be padded.minLength
- the length to reach.
-
rightPad
public static java.lang.String rightPad(java.lang.String s, int minLength, char filling)
Pads the string at the right with the specified character until it reaches the desired length. If the string is longer than this length, then it returns the unchanged string.- Parameters:
s
- the string that will be padded.minLength
- the length to reach.filling
- the filling pattern.
-
rightPad
public static java.lang.String rightPad(java.lang.String s, int minLength, java.lang.String filling)
Pads the string at the right with a filling pattern until it reaches the desired length. If the string is longer than this length, then it returns the unchanged string. For example:rightPad('ABC', 9, '1234')
returns"ABC412341"
. Note that the filling pattern is started as if you overlay"123412341"
with the left-aligned"ABC"
, so it starts with"4"
.- Parameters:
s
- the string that will be padded.minLength
- the length to reach.filling
- the filling pattern. Must be at least 1 characters long. Can't benull
.
-
versionStringToInt
public static int versionStringToInt(java.lang.String version)
Converts a version number string to an integer for easy comparison. The version number must start with numbers separated with dots. There can be any number of such dot-separated numbers, but only the first three will be considered. After the numbers arbitrary text can follow, and will be ignored. The string will be trimmed before interpretation.- Returns:
- major * 1000000 + minor * 1000 + micro
-
tryToString
public static java.lang.String tryToString(java.lang.Object object)
Tries to runtoString()
, but if that fails, returns a"[com.example.SomeClass.toString() failed: " + e + "]"
instead. Also, it returnsnull
fornull
parameter.- Since:
- 2.3.20
-
toUpperABC
public static java.lang.String toUpperABC(int n)
Converts1
,2
,3
and so forth to"A"
,"B"
,"C"
and so fort. When reaching"Z"
, it continues like"AA"
,"AB"
, etc. The lowest supported number is 1, but there's no upper limit.- Throws:
java.lang.IllegalArgumentException
- If the argument is 0 or less.- Since:
- 2.3.22
-
toLowerABC
public static java.lang.String toLowerABC(int n)
Same astoUpperABC(int)
, but produces lower case result, like"ab"
.- Since:
- 2.3.22
-
trim
public static char[] trim(char[] cs)
Behaves exactly likeString.trim()
, but works on arrays. If the resulting array would have the same content after trimming, it returns the original array instance. Otherwise it returns a new array instance (orCollectionUtils.EMPTY_CHAR_ARRAY
).- Since:
- 2.3.22
-
isTrimmableToEmpty
public static boolean isTrimmableToEmpty(char[] text)
Tells ifString.trim()
will return a 0-length string for theString
equivalent of the argument.- Since:
- 2.3.22
-
isTrimmableToEmpty
public static boolean isTrimmableToEmpty(char[] text, int start)
LikeisTrimmableToEmpty(char[])
, but acts on a sub-array that starts atstart
(inclusive index).- Since:
- 2.3.23
-
isTrimmableToEmpty
public static boolean isTrimmableToEmpty(char[] text, int start, int end)
LikeisTrimmableToEmpty(char[])
, but acts on a sub-array that starts atstart
(inclusive index) and ends atend
(exclusive index).- Since:
- 2.3.23
-
globToRegularExpression
public static java.util.regex.Pattern globToRegularExpression(java.lang.String glob)
- Since:
- 2.3.24
-
globToRegularExpression
public static java.util.regex.Pattern globToRegularExpression(java.lang.String glob, boolean caseInsensitive)
Creates a regular expression from a glob. The glob must use/
for as file separator, not\
(backslash), and is always case sensitive.This glob implementation recognizes these special characters:
?
: Wildcard that matches exactly one character, other than/
*
: Wildcard that matches zero, one or multiple characters, other than/
**
: Wildcard that matches zero, one or multiple directories. For example,**
/head.ftl
matchesfoo/bar/head.ftl
,foo/head.ftl
andhead.ftl
too.**
must be either preceded by/
or be at the beginning of the glob.**
must be either followed by/
or be at the end of the glob. When**
is at the end of the glob, it also matches file names, likea/**
matchesa/b/c.ftl
. If the glob only consist of a**
, it will be a match for everything.\
(backslash): Makes the next character non-special (a literal). For exampleHow\?.ftl
will matchHow?.ftl
, but notHowX.ftl
. Naturally, two backslashes produce one literal backslash.[
: Reserved for future purposes; can't be used{
: Reserved for future purposes; can't be used
- Since:
- 2.3.24
-
-