Method replaceFirst (line 32) replaces the first occurrence of a pattern match. In line 19, every match for the regular expression "stars" in firstString is replaced with "carets". So the Java string "\\*" represents the regular-expression pattern \* which matches a single * character in the search string. Since the expression is stored in a Java string and \ is a special character in Java strings, we must include an additional \. By escaping a special regular-expression character with a \, we instruct the regular-expression matching engine to find the actual character, as opposed to what it represents in a regular expression. However, in line 14, we want to find all occurrences of the literal character *to do this, we must escape character * with character \. Normally, * is a quantifier indicating that a regular expression should match any number of occurrences of a preceding pattern. Note that the regular expression ( "\\*") precedes character * with two backslashes, \. Line 14 replaces every instance of "*" in firstString with "^". Method replaceAll replaces text in a string with new text (the second argument) wherever the original string matches a regular expression (the first argument). "carets" substituted for "stars": This sentence ends inĮvery word replaced by "word": word word word word ^ substituted for *: This sentence ends in
0 Comments
Leave a Reply. |