简体   繁体   English

Javascript RegExp-匹配字符串并替换

[英]Javascript RegExp - Match String and Replace

I am very new to RegExp. 我是RegExp的新手。 What I am trying to do is: 我正在尝试做的是:

I have this original query condition. 我有这个原始查询条件。

var strQuery = "AND i.CreatedDate BETWEEN CAST('01/01/2014' AS Date) " +
    "AND DATEADD(Day, 1, CAST('01/01/2015' AS DATE) )   " +
    "AND e.User_ID IN (-1, 1234, 3433, 9999)  " +
    "AND i.STATUS IN ('Completed')  AND o.Type IN ('Production') "

Now, look for the string "e.User_ID IN (" and then replace anything between the parenthesis () with new IDs String. For example. 现在,查找字符串“ e.User_ID IN(”),然后用新的ID字符串替换括号()之间的任何内容。

var newUserIDs = "8888, 3333, 4444"

// After search and replace using RegExp.
var strQuery = "AND i.CreatedDate BETWEEN CAST('01/01/2014' AS Date) " +
    "AND DATEADD(Day, 1, CAST('01/01/2015' AS DATE) )   " +
    "AND e.User_ID IN (8888, 3333, 4444)  " +
    "AND i.STATUS IN ('Completed')  AND o.Type IN ('Production') "

Please help. 请帮忙。 Let me know if I am not clear since I am new to this. 如果我还不清楚,请告诉我。 Thanks in advance. 提前致谢。

You can simply concatenate like this. 您可以像这样简单地串联。

 var newUserIDs = "8888, 3333, 4444" // After search and replace using RegExp. var strQuery = "AND i.CreatedDate BETWEEN CAST('01/01/2014' AS Date) " + "AND DATEADD(Day, 1, CAST('01/01/2015' AS DATE) ) " + "AND e.User_ID IN (" + newUserIDs + ") " + "AND i.STATUS IN ('Completed') AND o.Type IN ('Production') " alert(strQuery); 

After all it's just a string. 毕竟这只是一个字符串。

Using regexp it would be like this: 使用regexp会像这样:

 var strQuery = "AND i.CreatedDate BETWEEN CAST('01/01/2014' AS Date) " + "AND DATEADD(Day, 1, CAST('01/01/2015' AS DATE) ) " + "AND e.User_ID IN (-1, 1234, 3433, 9999) " + "AND i.STATUS IN ('Completed') AND o.Type IN ('Production') "; var newUserIDs = "8888, 3333, 4444"; var newQuery = strQuery.replace(/User_ID IN \\([\\d, -]*\\)/,"User_ID IN (" + newUserIDs + ")"); alert(newQuery); 

You are searching for your cue, followed by 0 or more of any of the characters between [] surrounded by parenthesis. 您正在搜索提示,后面跟着[]中[]括起来的0或多个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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