Regular expression substitution string [javascript]__ regular expression

Source: Internet
Author: User

Requirements: "Ice \ Rain three Liu De \\\" Hua-----\\12 rain 3\\\\\\\\\\222222 "" \ "replaced by a | | and is only to replace \, can not replace more than two characters, for example, should only replace the ice rain between the middle of \ and--12 \.

Regular expression is my old friend, like it is about 07 time processing a publishing system tag read items, a long time useless, a little rusty. Encountered the problem of string processing, my first thought must be regular expression, eclipse also standing a regular plug-in, simple thinking after the:

Move directly to JavaScript and find that JavaScript does not support the writing of (? <!), that is, "reverse negation", which can only be done in other ways, and has:

	function Change (newstr) {
		//var reg =/(? <!\\) \\\\ (?! \)/g;
		var reg =/[^\\] (\\{2}) (?! \)/g;
		var str_before = ' ice \ Rain three Liu De \\\ ' hua-----\\12 rain 3\\\\\\\\\\222222 ';
		var str_before = ' Ice \\\\ rain three Liu De \\\\\\ ' hua-----\\\\12 rain 3\\\\\\\\\\\\\\\\\\\\222222 ';
		var str_after = Str_before.replace (REG,NEWSTR);
		alert (str_after);
	}

Write like this, not only will meet the conditions of the capture, will also be the front of a character capture to the brain a bit not bright, think for a long time, did not come up with a good method, and finally reverse thinking a bit, the character extracted and to replace the word is not a match. So there was:

	function Change (newstr) {
		//var reg =/(? <!\\) \\\\ (?! \)/g;
		var reg =/[^\\] (\\{2}) (?! \)/g;
		var str_before = ' ice \ Rain three Liu De \\\ ' hua-----\\12 rain 3\\\\\\\\\\222222 ';
		var str_before = ' Ice \\\\ rain three Liu De \\\\\\ ' hua-----\\\\12 rain 3\\\\\\\\\\\\\\\\\\\\222222 ';
		var str_after = str_before.replace (Reg, function (m) {
			m = m.substring (0, 1);
			return m + newstr;
		});
		alert (str_after);
	}
Basically meet the demand.

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.