Class Substring.Pattern
- Direct Known Subclasses:
Substring.Prefix
,Substring.Suffix
- Enclosing class:
Substring
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionfinal Substring.Pattern
followedBy
(String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring be immediately followed by thelookahead
string.from
(CharSequence string) Matches this pattern againststring
, returning the matched substring if successful, orempty()
otherwise.final Substring.Pattern
immediatelyBetween
(String lookbehind, Substring.BoundStyle lookbehindBound, String lookahead, Substring.BoundStyle lookaheadBound) Similar toimmediatelyBetween(String, String)
, but allows including thelookbehind
and/orlookahead
inclusive in the match.final Substring.Pattern
immediatelyBetween
(String lookbehind, String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring be immediately preceded by thelookbehind
string and immediately followed by theafter
string.final Optional
<Substring.Match> Matches this pattern againststring
, returning aMatch
if successful, orempty()
otherwise.final Optional
<Substring.Match> Matches this pattern againststring
starting from the character atfromIndex
, returning aMatch
if successful, orempty()
otherwise.limit
(int maxChars) Returns aPattern
that's equivalent to this pattern except it only matches at mostmaxChars
.final Substring.Pattern
notFollowedBy
(String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring not be immediately followed by thelookahead
string.final Substring.Pattern
notImmediatelyBetween
(String lookbehind, String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring not be immediately preceded by thelookbehind
string and immediately followed by theafter
string.final Substring.Pattern
notPrecededBy
(String lookbehind) Returns an otherwise equivalent pattern except it requires the matched substring not be immediately preceded by thelookbehind
string.final Substring.Pattern
or
(Substring.Pattern that) Returns aPattern
that falls back to usingthat
ifthis
fails to match.peek
(Substring.Pattern following) Return aPattern
equivalent to thisPattern
, except it will fail to match if thefollowing
pattern can't find a match in the substring after the current match.final Substring.Pattern
precededBy
(String lookbehind) Returns an otherwise equivalent pattern except it requires the matched substring be immediately preceded by thelookahead
string.final String
removeFrom
(String string) Matches this pattern againststring
, and returns a copy with the matched substring removed if successful.Returns aSubstring.RepeatingPattern
that applies this pattern repeatedly against the input string.final String
replaceFrom
(String string, CharSequence replacement) Returns a new string with the substring matched bythis
replaced byreplacement
.final String
replaceFrom
(String string, Function<? super Substring.Match, ? extends CharSequence> replacementFunction) Returns a new string with the substring matched bythis
replaced by the return value ofreplacementFunction
.final Substring.Pattern
separatedBy
(CharPredicate separator) Returns an otherwise equivalentPattern
, except it only matches if it's next to the beginning of the string, the end of the string, or theseparator
character(s).separatedBy
(CharPredicate separatorBefore, CharPredicate separatorAfter) Returns an otherwise equivalentPattern
, except it requires the beginning of the match must either be the beginning of the string, or be separated from the rest of the string by theseparatorBefore
character; and the end of the match must either be the end of the string, or be separated from the rest of the string by theseparatorAfter
character.skip
(int fromBeginning, int fromEnd) Returns aPattern
that's equivalent to this pattern except it will skip up tofromBeginnings
characters from the beginning of the match and up tofromEnd
characters from the end of the match.final BiOptional
<String, String> split
(CharSequence string) Splitsstring
into two parts that are separated by this separator pattern.final BiOptional
<String, String> splitThenTrim
(CharSequence string) Splitsstring
into two parts that are separated by this separator pattern, with leading and trailing whitespaces trimmed.final Substring.Pattern
then
(Substring.Pattern following) Similar to regex lookahead, returns a pattern that matches thefollowing
pattern after it has matched this pattern.final Substring.Pattern
toEnd()
Returns aPattern
that will match from the substring matched bythis
to the end of the input string.toString()
Do not depend on the string representation of Substring, except for subtypesSubstring.Prefix
andSubstring.Suffix
that have an explicitly defined representation.
-
Constructor Details
-
Pattern
public Pattern()
-
-
Method Details
-
in
Matches this pattern againststring
, returning aMatch
if successful, orempty()
otherwise.This is useful if you need to call
Substring.Match
methods, likeSubstring.Match.remove()
orSubstring.Match.before()
. If you just need the matched substring itself, prefer to usefrom(java.lang.CharSequence)
instead. -
in
Matches this pattern againststring
starting from the character atfromIndex
, returning aMatch
if successful, orempty()
otherwise.Note that it treats
fromIndex
as the beginning of the string, so patterns likeSubstring.prefix(java.lang.String)
,Substring.BEGINNING
will attempt to match from this index.- Throws:
IndexOutOfBoundsException
- if fromIndex is negative or greater thanstring.length()
- Since:
- 7.0
-
from
Matches this pattern againststring
, returning the matched substring if successful, orempty()
otherwise.pattern.from(str)
is equivalent topattern.in(str).map(Object::toString)
.This is useful if you only need the matched substring itself. Use
in(java.lang.String)
if you need to callSubstring.Match
methods, likeSubstring.Match.remove()
orSubstring.Match.before()
. -
removeFrom
Matches this pattern againststring
, and returns a copy with the matched substring removed if successful. Otherwise, returnsstring
unchanged. -
replaceFrom
Returns a new string with the substring matched bythis
replaced byreplacement
. Returnsstring
as-is if a substring is not found. -
replaceFrom
public final String replaceFrom(String string, Function<? super Substring.Match, ? extends CharSequence> replacementFunction) Returns a new string with the substring matched bythis
replaced by the return value ofreplacementFunction
.For example, you can replace a single template placeholder using:
Substring.spanningInOrder("{", "}") .replaceFrom(s, placeholder -> replacements.get(placeholder.skip(1, 1).toString()));
Returns
string
as-is if a substring is not found.- Since:
- 5.6
-
toEnd
Returns aPattern
that will match from the substring matched bythis
to the end of the input string. For example:String line = "return foo; // some comment..."; String commentRemoved = first("//").toEnd().removeFrom(line).trim(); assertThat(commentRemoved).isEqualTo("return foo;");
To match from the beginning of the input string to the end of a pattern, use
Substring.upToIncluding(com.google.mu.util.Substring.Pattern)
instead. -
or
Returns aPattern
that falls back to usingthat
ifthis
fails to match. -
limit
Returns aPattern
that's equivalent to this pattern except it only matches at mostmaxChars
.- Since:
- 6.1
-
skip
Returns aPattern
that's equivalent to this pattern except it will skip up tofromBeginnings
characters from the beginning of the match and up tofromEnd
characters from the end of the match.If the match includes fewer characters, an empty match is returned.
- Since:
- 6.1
-
then
Similar to regex lookahead, returns a pattern that matches thefollowing
pattern after it has matched this pattern. For examplefirst('/').then(first('/'))
finds the second '/' character.- Since:
- 5.7
-
peek
Return aPattern
equivalent to thisPattern
, except it will fail to match if thefollowing
pattern can't find a match in the substring after the current match.Useful in asserting that the current match is followed by the expected pattern. For example:
SCHEME_NAME.peek(prefix(':'))
returns the URI scheme name.Note that unlike regex lookahead, no backtracking is attempted. So
first("foo").peek("bar")
will match "bafoobar" but won't match "foofoobar" because the first "foo" isn't followed by "bar".If look-ahead is needed, you can use
followedBy(java.lang.String)
as infirst("foo").followedBy("bar")
.If you are trying to define a boundary around or after your pattern similar to regex anchor
'\b'
, consider usingseparatedBy(com.google.mu.util.CharPredicate)
if the boundary can be detected by a character.- Since:
- 6.0
-
separatedBy
Returns an otherwise equivalentPattern
, except it only matches if it's next to the beginning of the string, the end of the string, or theseparator
character(s).Useful if you are trying to find a word with custom boundaries. To search for words composed of regex
\w
character class, consider usingSubstring.word()
instead.For lookahead and lookbehind assertions, consider using
immediatelyBetween(java.lang.String, java.lang.String)
orfollowedBy(java.lang.String)
instead.- Since:
- 6.2
-
separatedBy
Returns an otherwise equivalentPattern
, except it requires the beginning of the match must either be the beginning of the string, or be separated from the rest of the string by theseparatorBefore
character; and the end of the match must either be the end of the string, or be separated from the rest of the string by theseparatorAfter
character.Useful if you are trying to find a word with custom boundaries. To search for words composed of regex
\w
character class, consider usingSubstring.word()
instead.For lookahead and lookbehind assertions, consider using
Substring.between(java.lang.String, java.lang.String)
orfollowedBy(java.lang.String)
instead.- Since:
- 6.2
-
immediatelyBetween
Returns an otherwise equivalent pattern except it requires the matched substring be immediately preceded by thelookbehind
string and immediately followed by theafter
string.Similar to regex lookarounds, the returned pattern will backtrack until the lookaround is satisfied. That is,
word().immediatelyBetween("(", ")")
will find the "bar" substring inside the parenthesis from "foo (bar)".If you need lookahead only, use
followedBy(java.lang.String)
instead; for lookbehind only, pass an empty string as thelookahead
string, as in:word().immediatelyBetween(":", "")
.- Since:
- 6.2
-
immediatelyBetween
public final Substring.Pattern immediatelyBetween(String lookbehind, Substring.BoundStyle lookbehindBound, String lookahead, Substring.BoundStyle lookaheadBound) Similar toimmediatelyBetween(String, String)
, but allows including thelookbehind
and/orlookahead
inclusive in the match.For example, to split around all "{placholder_name}", you can use:
PLACEHOLDER_NAME_PATTERN.immediatelyBetween("{", INCLUSIVE, "}", INCLUSIVE) .split(input);
- Since:
- 7.0
-
notImmediatelyBetween
Returns an otherwise equivalent pattern except it requires the matched substring not be immediately preceded by thelookbehind
string and immediately followed by theafter
string.Similar to regex negative lookarounds, the returned pattern will backtrack until the negative lookaround is satisfied. That is,
word().notImmediatelyBetween("(", ")")
will find the "bar" substring from "(foo) bar".If you need negative lookahead only, use
notFollowedBy(java.lang.String)
instead; for negative lookbehind only, pass an empty string as thelookahead
string, as in:word().notImmediatelyBetween(":", "")
.If the pattern shouldn't be preceded or followed by particular character(s), consider using
separatedBy(com.google.mu.util.CharPredicate)
. The following code finds "911" but only if it's at the beginning of a number:Substring.Pattern emergency = first("911").separatedBy(CharPredicate.range('0', '9').not(), CharPredicate.ANY);
- Since:
- 6.2
-
followedBy
Returns an otherwise equivalent pattern except it requires the matched substring be immediately followed by thelookahead
string.Similar to regex negative lookahead, the returned pattern will backtrack until the lookahead is satisfied. That is,
word().followedBy(":")
will find the "Joe" substring from "To Joe:".If you need lookbehind, or both lookahead and lookbehind, use
immediatelyBetween(java.lang.String, java.lang.String)
instead.- Since:
- 6.2
-
notFollowedBy
Returns an otherwise equivalent pattern except it requires the matched substring not be immediately followed by thelookahead
string.Similar to regex negative lookahead, the returned pattern will backtrack until the negative lookahead is satisfied. That is,
word().notFollowedBy(" ")
will find the "Joe" substring from "To Joe:".If you need negative lookbehind, or both negative lookahead and lookbehind, use
notImmediatelyBetween(java.lang.String, java.lang.String)
instead.If the pattern shouldn't be followed by particular character(s), consider using
separatedBy(com.google.mu.util.CharPredicate)
. The following code finds the file extension name ".java" if it's not followed by another letter:CharPredicate letter = Character::isJavaIdentifierStart; Substring.Pattern javaExtension = first(".java").separatedBy(CharPredicate.ANY, letter.not());
- Since:
- 6.2
-
precededBy
Returns an otherwise equivalent pattern except it requires the matched substring be immediately preceded by thelookahead
string.Similar to regex lookbehind, the returned pattern will backtrack until the lookbehind is satisfied. That is,
word().precededBy(": ")
will find the "Please" substring from "Amy: Please come in".- Since:
- 6.2
-
notPrecededBy
Returns an otherwise equivalent pattern except it requires the matched substring not be immediately preceded by thelookbehind
string.Similar to regex negative lookbehind, the returned pattern will backtrack until the negative lookbehind is satisfied. For example,
word().notPrecededBy("(")
will find the "bar" substring from "(foo+bar)".- Since:
- 6.2
-
split
Splitsstring
into two parts that are separated by this separator pattern. For example:Optional<KeyValue> keyValue = first('=').split("name=joe").join(KeyValue::new);
If you need to trim the key-value pairs, use
splitThenTrim(java.lang.CharSequence)
.To split a string into multiple substrings delimited by a delimiter, use
repeatedly()
.- Since:
- 5.0
-
splitThenTrim
Splitsstring
into two parts that are separated by this separator pattern, with leading and trailing whitespaces trimmed. For example:Optional<KeyValue> keyValue = first('=').splitThenTrim("name = joe ").join(KeyValue::new);
If you are trying to parse a string to a key-value data structure (
Map
,Multimap
etc.), you can usecom.google.common.base.Splitter.MapSplitter
though it's limited toMap
and doesn't allow duplicate keys:
Alternatively, you can useString toSplit = " x -> y, z-> a "; Map<String, String> result = Splitter.on(',') .trimResults() .withKeyValueSeparator(Splitter.on("->")) .split(toSplit);
Substring
to allow duplicate keys and to split into multimaps or other types:import static com.google.mu.util.stream.MoreCollectors.mapping; String toSplit = " x -> y, z-> a, x -> t "; ImmutableListMultimap<String, String> result = first(',') .repeatedly() .split(toSplit) .map(first("->")::splitThenTrim) .collect( mapping( kv -> kv.orElseThrow(...), ImmutableListMultimap::toImmutableListMultimap));
To split a string into multiple substrings delimited by a delimiter, use
repeatedly()
.- Since:
- 5.0
-
repeatedly
Returns aSubstring.RepeatingPattern
that applies this pattern repeatedly against the input string. That is, after each iteration, the pattern is applied again over the substring after the match, repeatedly until no match is found.- Since:
- 5.2
-
toString
Do not depend on the string representation of Substring, except for subtypesSubstring.Prefix
andSubstring.Suffix
that have an explicitly defined representation.
-