简体   繁体   中英

What's the difference between these similar Java regexes?

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
    • one or more digits at the begin of a line (note m modifier in (?m) ), followed by
    • a literal . , followed by
    • zero or more whitespace characters (equivalent to [ \\t\\n\\x0B\\f\\r] );
  • ^[0-9]+\\\\. * ^[0-9]+\\\\. * matches
    • one or more digits at the begin of the string , followed by
    • a literal . , followed by
    • zero of more spaces ;
  • \\\\d+\\.\\\\s+ matches
    • one or more digits at any position , followed by
    • a literal . , followed by
    • one or more whitespace characters .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM