Class Substring.Pattern
- Direct Known Subclasses:
Substring.Prefix,Substring.Suffix
- Enclosing class:
Substring
- Since:
- 2.0
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal Substring.PatternfollowedBy(String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring be immediately followed by thelookaheadstring.from(CharSequence string) Matches this pattern againststring, returning the matched substring if successful, orempty()otherwise.final Substring.PatternimmediatelyBetween(String lookbehind, Substring.BoundStyle lookbehindBound, String lookahead, Substring.BoundStyle lookaheadBound) Similar toimmediatelyBetween(String, String), but allows including thelookbehindand/orlookaheadinclusive in the match.final Substring.PatternimmediatelyBetween(String lookbehind, String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring be immediately preceded by thelookbehindstring and immediately followed by theafterstring.final Optional<Substring.Match> Matches this pattern againststring, returning aMatchif successful, orempty()otherwise.final Optional<Substring.Match> Matches this pattern againststringstarting from the character atfromIndex, returning aMatchif successful, orempty()otherwise.limit(int maxChars) Returns aPatternthat's equivalent to this pattern except it only matches at mostmaxChars.final Substring.PatternnotFollowedBy(String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring not be immediately followed by thelookaheadstring.final Substring.PatternnotImmediatelyBetween(String lookbehind, String lookahead) Returns an otherwise equivalent pattern except it requires the matched substring not be immediately preceded by thelookbehindstring and immediately followed by theafterstring.final Substring.PatternnotPrecededBy(String lookbehind) Returns an otherwise equivalent pattern except it requires the matched substring not be immediately preceded by thelookbehindstring.final Substring.Patternor(Substring.Pattern that) Returns aPatternthat falls back to usingthatifthisfails to match.peek(Substring.Pattern following) Return aPatternequivalent to thisPattern, except it will fail to match if thefollowingpattern can't find a match in the substring after the current match.final Substring.PatternprecededBy(String lookbehind) Returns an otherwise equivalent pattern except it requires the matched substring be immediately preceded by thelookaheadstring.final StringremoveFrom(String string) Matches this pattern againststring, and returns a copy with the matched substring removed if successful.Returns aSubstring.RepeatingPatternthat applies this pattern repeatedly against the input string.final StringreplaceFrom(String string, CharSequence replacement) Returns a new string with the substring matched bythisreplaced byreplacement.final StringreplaceFrom(String string, Function<? super Substring.Match, ? extends CharSequence> replacementFunction) Returns a new string with the substring matched bythisreplaced by the return value ofreplacementFunction.final Substring.PatternseparatedBy(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 theseparatorcharacter(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 theseparatorBeforecharacter; and the end of the match must either be the end of the string, or be separated from the rest of the string by theseparatorAftercharacter.skip(int fromBeginning, int fromEnd) Returns aPatternthat's equivalent to this pattern except it will skip up tofromBeginningscharacters from the beginning of the match and up tofromEndcharacters from the end of the match.final BiOptional<String, String> split(CharSequence string) Splitsstringinto two parts that are separated by this separator pattern.final <T> Optional<T> split(CharSequence string, BiFunction<? super String, ? super String, ? extends T> mapper) Splitsstringinto two parts that are separated by this separator pattern.final BiOptional<String, String> splitThenTrim(CharSequence string) Splitsstringinto two parts that are separated by this separator pattern, with leading and trailing whitespaces trimmed.final <T> Optional<T> splitThenTrim(CharSequence string, BiFunction<? super String, ? super String, ? extends T> mapper) Splitsstringinto two parts that are separated by this separator pattern, with leading and trailing whitespaces trimmed.final Substring.Patternthen(Substring.Pattern following) Similar to regex lookahead, returns a pattern that matches thefollowingpattern after it has matched this pattern.final Substring.PatterntoEnd()Returns aPatternthat will match from the substring matched bythisto the end of the input string.toString()Do not depend on the string representation of Substring, except for subtypesSubstring.PrefixandSubstring.Suffixthat have an explicitly defined representation.
-
Constructor Details
-
Pattern
public Pattern()
-
-
Method Details
-
in
Matches this pattern againststring, returning aMatchif successful, orempty()otherwise.This is useful if you need to call
Substring.Matchmethods, 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 againststringstarting from the character atfromIndex, returning aMatchif successful, orempty()otherwise.Note that it treats
fromIndexas the beginning of the string, so patterns likeSubstring.prefix(java.lang.String),Substring.BEGINNINGwill 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.Matchmethods, likeSubstring.Match.remove()orSubstring.Match.before(). -
removeFrom
-
replaceFrom
Returns a new string with the substring matched bythisreplaced byreplacement. Returnsstringas-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 bythisreplaced 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
stringas-is if a substring is not found.- Since:
- 5.6
-
toEnd
Returns aPatternthat will match from the substring matched bythisto 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 aPatternthat falls back to usingthatifthisfails to match. -
limit
Returns aPatternthat's equivalent to this pattern except it only matches at mostmaxChars.- Since:
- 6.1
-
skip
Returns aPatternthat's equivalent to this pattern except it will skip up tofromBeginningscharacters from the beginning of the match and up tofromEndcharacters 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 thefollowingpattern after it has matched this pattern. For examplefirst('/').then(first('/'))finds the second '/' character.This method is soft-deprecated. It's prone to misuse. You should usually use other methods to achieve similar effects.
- Since:
- 5.7
-
peek
Return aPatternequivalent to thisPattern, except it will fail to match if thefollowingpattern 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.This method is soft-deprecated. It's prone to misuse. You should usually use other methods to achieve similar effects.
- 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 theseparatorcharacter(s).Useful if you are trying to find a word with custom boundaries. To search for words composed of regex
\wcharacter 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 theseparatorBeforecharacter; and the end of the match must either be the end of the string, or be separated from the rest of the string by theseparatorAftercharacter.Useful if you are trying to find a word with custom boundaries. To search for words composed of regex
\wcharacter 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 thelookbehindstring and immediately followed by theafterstring.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 thelookaheadstring, 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 thelookbehindand/orlookaheadinclusive 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 thelookbehindstring and immediately followed by theafterstring.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 thelookaheadstring, 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 thelookaheadstring.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 thelookaheadstring.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 thelookaheadstring.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 thelookbehindstring.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
public final <T> Optional<T> split(CharSequence string, BiFunction<? super String, ? super String, ? extends T> mapper) Splitsstringinto two parts that are separated by this separator pattern. For example:Optional<KeyValue> keyValue = first('=').split("name=joe", KeyValue::new);If
thispattern isn't found instringor if themapperfunction returns null,Optional.empty()is returned.If you need to trim the key-value pairs, use
splitThenTrim().To split a string into multiple substrings delimited by a delimiter, use
repeatedly().- Since:
- 9.4
-
split
Splitsstringinto two parts that are separated by this separator pattern. For example:Optional<KeyValue> keyValue = first('=').split("name=joe").map(KeyValue::new);If you need to trim the key-value pairs, use
splitThenTrim(CharSequence).To split a string into multiple substrings delimited by a delimiter, use
repeatedly().- Since:
- 5.0
-
splitThenTrim
public final <T> Optional<T> splitThenTrim(CharSequence string, BiFunction<? super String, ? super String, ? extends T> mapper) Splitsstringinto two parts that are separated by this separator pattern, with leading and trailing whitespaces trimmed. For example:Optional<KeyValue> keyValue = first('=').splitThenTrim("name = joe ", KeyValue::new);If
thispattern isn't found instringor if themapperfunction returns null,Optional.empty()is returned.To split a string into multiple substrings delimited by a delimiter, use
repeatedly().- Since:
- 9.4
-
splitThenTrim
Splitsstringinto two parts that are separated by this separator pattern, with leading and trailing whitespaces trimmed. For example:Optional<KeyValue> keyValue = first('=').splitThenTrim("name = joe ").map(KeyValue::new);If you are trying to parse a string to a key-value data structure (
Map,Multimapetc.), you can usecom.google.common.base.Splitter.MapSplitterthough it's limited toMapand 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);Substringto 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 = all(',') .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.RepeatingPatternthat 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.PrefixandSubstring.Suffixthat have an explicitly defined representation.
-