简体   繁体   English

替换两个单词之间的文字

[英]Replace text between two words

This question seems to be simple and repetitive here in SO. 在SO中,这个问题似乎很简单,也很重复。

But consider this string: SELECT a, b, c, d FROM . 但请考虑这个字符串: SELECT a, b, c, d FROM I want to get only what is between SELECT and FROM . 我想得到SELECTFROM之间的内容。

Nice so I have found this answer that propose this regex: (?<=SELECT)(.*)(?=FROM) . 很好,所以我找到了这个答案提出这个正则表达式: (?<=SELECT)(.*)(?=FROM) It's perfect if lookbehind works in JavaScript, according to this post : 根据这篇文章 ,如果lookbehind在JavaScript中工作,这是完美

Unlike lookaheads, JavaScript doesn't support regex lookbehind syntax 与前瞻不同,JavaScript不支持正则表达式的lookbehind语法

So it won't work(test it in regexpal that is made for JS). 所以它不起作用(在为JS制作的regexpal中测试它)。 This anwser proposes this regex: SELECT=(.*?)FROM . 这个anwser提出了这个正则表达式: SELECT=(.*?)FROM But it includes the two words, so it not fits my needs. 但它包括两个词,所以它不符合我的需要。

The purpose of this is to use in a replace function to transform this... 这样做的目的是在replace函数中使用来改变这个......

SELECT a, b, c, d FROM

into this... 进入这...

SELECT Count(*) FROM

Thank you in advance. 先感谢您。

只需使用捕获组:

"SELECT a, b, c, d FROM".replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)")

Try this:- 尝试这个:-

$("button").click(function() {
var srctext = $("#fixme").text();
console.log("old text: " + srctext);

var newtext = srctext.replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)");
console.log("new text: " + newtext);

$("#fixme").text(newtext)
});

WORKING JSFIDDLE:- http://jsfiddle.net/tkP74/1597/ 工作JSFIDDLE: - http://jsfiddle.net/tkP74/1597/

好吧,你可以像我在评论中所说的那样把SELECT放回去:

str.replace(/SELECT (.*?)(?= FROM)/i, "SELECT Count(*)");

正如此特定字符串的正则表达式的替代方法:

str = 'SELECT COUNT(*) ' + str.substr(str.indexOf('FROM'));

Without regex : 没有正则表达式

var query = "SELECT a, b, c, d FROM";
var iSelect = query.indexOf("SELECT");
var selLen = "SELECT".length;
var iFrom = query.indexOf("FROM");
if (iSelect >= 0 && iFrom >= 0) {
    query = query.replace(query.substring(iSelect + selLen, iFrom), " COUNT(*) ");
    console.log(query);
}

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

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