问题
I'm trying to come up with a regular expression which will search for a string and replace with new set of characters. My string is something like this.
(Product=='Partnership - CT'&&State==CT)
Here I have to search for the CT
value for state key and replace with 'CT'
(i.e., add single quotation marks). I have used the following Regexp in JavaScript.
var expressionQuery = "(Product=='Partnership - CT'&&State==CT)";
val = 'CT';
expressionQuery.replace(new RegExp(val, "g"),"\'"+val+"\'" );
But this is giving output as (Product=='Partnership - 'CT''&&State=='CT')
Expected output : (Product=='Partnership - CT'&&State=='CT')
That is, I only want to change the instance of CT that appears immediately after ==. Please help me to write the expression to fix this.
回答1:
UPDATE: You don't have to hardcode the "CT" in your regular expression. If you know that the "State" parameter will always be a two-letter code you can add quotation marks to any state with something like the following:
expressionQuery.replace(/State==([A-Z]{2})/g,"State=='$1'");
This says to find a the substring "State==" followed by any two letters, and then in the replace expression where it has "$1" that means insert whatever matched the part of the regex in parentheses. Note that because it specifically looks for a letter after "==" it won't add extra quotation marks if they were already present.
And my original answer, which replaces only the specified state (whether hardcoded or otherwise indicated by a variable):
You could go for non-capturing matches on the "==" and so forth, but I think it would be easier to just include "==" in both the search and replace text:
var expressionQuery = "(Product=='Partnership - CT'&&State==CT)",
val = "CT";
expressionQuery.replace(new RegExp("==" + val, "g"),"=='"+val+"'" );
Or you may even want to include "State" in the search, in case you later have other parameters that might match, like "SomeOtherParam==CT":
expressionQuery.replace(new RegExp("State==" + val, "g"),"State=='"+val+"'" );
Note that you don't need to escape single quotation marks if they are in a string quoted with doubles. I.e., "'"
does the same thing as "\'"
.
(Note also that your original code was invalid because you forgot to put any quotation marks around the string in your declaration of expressionQuery
.)
回答2:
You could use a negative lookahead to ensure that there is no '
ahead of the pattern you want to replace.
expressionQuery.replace(new RegExp('CT(?!\')', "g"),"\'"+val+"\'" );
It works for your example, but I don't know if this rule is strict enough to avoid false replacements in all cases.
来源:https://stackoverflow.com/questions/8586010/javascript-regexp-to-replace-a-value-only-when-it-follows-certain-characters