Are these three related Java regexes just different syntaxes for doing the same thing?
String resultString = subjectString.replaceAll("(?m)^\\d+\\.\\s*", "");
String resultString = subjectString.replace("^[0-9]+\\. *", "");
String resultString = subjectString.replaceAll('\\d+\.\\s+', '');
replace
doesn't accept a regexp; it accepts a literal string (ie will really search for exactly those characters). replaceAll
accepts a regexp.
The third one isn't valid because single quotes are used. Single quotes represent individual characters which are char
. Double quotes create strings (multiple characters) which are String
s.
No, they are different:
(?m)^\\\\d+\\\\.\\\\s*
matches
(?m)
), followed by .
, followed by [ \\t\\n\\x0B\\f\\r]
); ^[0-9]+\\\\. *
^[0-9]+\\\\. *
matches
.
, followed by \\\\d+\\.\\\\s+
matches
.
, followed by Besides that, as Adrian Smith has noted , replace
does not expect a regular expression but a single char or a CharacterSequence ( String implements that interface).
Close, each replace a number followed by a period followed by white-space , ie 11.
. But each one has slight difference:
The first will replace requires that the digit be at the beginning of a line and the white-space can be anything, ie a tab.
The second isn't valid, as noted, but if it were replaceAll()
the white-space could only be the space character.
The third doesn't have to be at the beginning of the line and will replace any white-space characters like the first one.
The other differences are simply syntax.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.