Go The difference between String.Replace and String.replaceall

Source: Internet
Author: User

 

Replace ReplaceAll in JAVA

Problem:

Test code

  system.out.println ("1234567890abcdef----->" + "1234567890abcdef". Replace ("12345", "ABCDE" ));
  system.out.println ("1234567890abcdef----->" + "1234567890abcdef". ReplaceAll ("12345", "ABCDE")) ;
  system.out.println (" [email  Protected] #$%^&* ()-=abcd -----> "+" [email protected] #$%^&* ()-=abcd ". Replace (" #$% ^& "," OK ");
  system.out.println (" [email  Protected] #$%^&* ()-=abcd -----> "+" [email protected] #$%^&* ()-=abcd ". ReplaceAll (" #$% ^& "," OK ");
Execution Result:

1234567890abcdef-----> Abcde67890abcdef Replace replaces the target code successfully
1234567890abcdef-----> Abcde67890abcdef replaceall also successfully replaced the target code
[email protected]#$%^&* ()-=ABCD-----> [email protected]* ()-=ABCDReplace replaces the target code successfully
[email protected]#$%^&* ()-=ABCD-----> [email protected]#$%^&* ()-=ABCDReplaceAll Target Code substitutionfailed

It is obvious that String.replaceall has some differences with string.replace in the substitution of special characters.


Defined:
Replace

Public String replace (charsequence target, charsequence replacement)

Replaces the substring of the target sequence of all matching literals of this string with the specified literal substitution sequence. The substitution executes from the beginning of the string toward the end, for example, substituting "B" for "AA" in the string "AAA" to generate "BA" instead of "AB".
Parameters:

Target-the sequence of char values to be replaced

The replacement sequence of the Replacement-char value

Return:
Resulting String
Thrown:

NullPointerException

-If target or replacement is null.

ReplaceAll

public string ReplaceAll (string regex, string replacement)

Replaces this string with the given replacement for all substrings that match the given regular expression.

The str. ReplaceAll (regex, repl) form that calls this method is identical to the result of the following expression:

Pattern.compile (

Regex ). Matcher ( str ). ReplaceAll ( repl )

Note that using the backslash (\) and dollar sign ($) in an alternate string may be different from the result of substituting the string as a literal value; see Matcher.replaceall. If necessary, use Matcher.quotereplacement (java.lang.String)

Cancels the special meaning of these characters.

Parameters:

Regex-a regular expression used to match this string

Replacement-a string to replace each match

Return:
Resulting String
Thrown:

Patternsyntaxexception-If the syntax of the regular expression is invalid

It can be found that string.replace is mainly for the substitution of strings, and String.replaceall is mainly replaced with substrings of regular expressions. Therefore, when using String.replaceall, you cannot use it with the String.Replace method.

Can be String.replaceall (pattern.quote ("str1"), "str2");

that is:
  system.out.println (" 1234567890abcdef-----> "+" 1234567890abcdef ". Replace (" 12345 "," ABCDE "));
  system.out.println ("1234567890abcdef----->" + "1234567890abcdef". ReplaceAll ("12345", "ABCDE")) ;
  system.out.println ("[email protected" #$%^&* ()-=ABCD-----> "+" [email protected] #$%^&* ()-=abcd ". Replace (" #$%^& "," OK "));
  system.out.println ("[email protected" #$%^&* ()-=ABCD-----> "+" [email protected] #$%^&* ()-=abcd ". ReplaceAll (Pattern.quote (" #$%^& ")," OK ");

Replace in JAVASCRIPT does not provide ReplaceAll

Stringobj.replace (Rgexp, ReplaceText)

Parameters
Stringobj
Required option. A string object or string literal to perform the substitution. The string is not modified by the Replace method.
Rgexp
Required option. is a regular expression object that contains a regular expression pattern or an available flag. It can also be a String object or literal. If Rgexp is not a regular expression object, it will be converted to a string, and the exact lookup is done, and do not attempt to convert the string to a regular expression.
ReplaceText
Required option. is a string object or string literal, and the position in each matching rgexp in Stringobj is replaced with the text contained by the object. In Jscript 5.5 or later, the ReplaceText parameter can also be a function that returns alternate text.

Description
The result of the Replace method is a copy of the Stringobj object that completed the specified substitution.

Any of the following matching variables can be used to identify the most recent match and find the matching string. Match variables can be used in text substitutions that require dynamic decision substitution strings.

Character meaning
$$ $ (JScript 5.5 or later)
$& Specifies the portion of the stringobj that matches the entire pattern. (JScript 5.5 or later)
$ ' Specifies the stringobj part before the match described by $&. (JScript 5.5 or later)
$ ' Specifies the stringobj part after the match described by $&. (JScript 5.5 or later)
The nth sub-match $n capture, where n is a decimal digit from 1 to 9. (JScript 5.5 or later)
$nn the captured nn sub-match, where nn is a decimal two-digit number from 01 to 99. (JScript 5.5 or later)

If ReplaceText is a function, for each matched substring, the function is called with the following m+3 parameters, where m is the number of left brackets captured in Rgexp. The first parameter is a matching substring. The next m parameter is all the results captured in the lookup. The m+2 parameter is the offset that occurs in the stringobj, and the m+3 parameter is stringobj. The result is a string value that replaces each matched substring with the corresponding return value of the function call.

The Replace method updates the properties of the global RegExp object.

Example
The following example shows that the Replace method replaces the first occurrence of the word "the" with the use of the word "A".

function Replacedemo () {
var r, re; Declares a variable.
var ss = "The man hits the ball with the BAT.N";
SS + = "While the fielder caught the ball with the glove.";
re =/the/g; Creates a regular expression pattern.
r = Ss.replace (Re, "A"); Replace "A" with "A".
return (R); Returns the replaced string.

Get results:A man hits the ball with the bat.nwhile the fielder caught the ball with the glove.
In addition, the Replace method can replace sub-expressions in a pattern. The following example shows each pair of words in the interchange string:

function Replacedemo () {
var r, re; Declares a variable.
var ss = "The rain in Spain falls mainly in the plain.";
Re =/(\s+) (\s+) (\s+)/g; Creates a regular expression pattern.
r = Ss.replace (Re, "$3$2$1"); Exchange each pair of words.
return (R); Returns the result string.
}
Get the result :Rain The Spain in mainly falls the in plain.
The following example (executed in JScript 5.5 and later) performs a conversion from Fahrenheit to Celsius, demonstrating the use of functions as replacetext. To know how the function works, pass a string containing a numeric value followed by "F" (for example, "Water boils at 212").
var s = "Water freezes at 32F and boils at 212F."
var test =/(d+ (. d*)?) fb/g; Initialization mode.
Return (S.replace
(Test,
function ($0,$1,$2) {
Return ((($1-32) * 5/9) + "C");
}
)
);
Results obtained:water freezes at 0C and boils at 100C.
JS incredibly does not provide ReplaceAll method, with for loop and efficiency problem, give you a regular expression solution

JS Code
String.prototype.replaceAll = function (S1,S2) {
Return This.replace (New RegExp (S1, "GM"), S2);
}
Method: String.Replace (New RegExp (oldstring, "GM"), newstring))

GM G=global, M=multiline, roughly the way it is, can be implemented to replace all specified strings

Another simple way to verify JS:

Enter in the browser address bar
Javascript:alert ("Abcabcabc". Replace (new RegExp ("A", "GM"), "ad")

It's easier to do this, and I don't know if it will be convenient to do more.

Orgstr.replace (New RegExp (FindStr, ' G '), REPLACESTR)
We should be able to replace all of them.
If you don't use regular expressions
Orgstr.replace (FINDSTR, REPLACESTR) can only replace the first one

& Alternative <,>, ", ',&

*/

function Totxt (str) {

var rexstr =/\<|\>|\ "|\ ' |\&/g

str = str.replace (REXSTR,

function (MATCHSTR) {

Switch (MATCHSTR) {

Case "<":

return "& lt;";

Break

Case ">":

Return "& gt;";

Break

Case "\" ":

return "& quot;";

Break

Case "'":

Return "& #39;";

Break

Case "&":

Return "& amp;";

Break

Default:

Break

}

}

)

return str;

}

Go The difference between String.Replace and String.replaceall

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.