2

This question seems to be simple and repetitive here in SO.

But consider this string: SELECT a, b, c, d FROM. I want to get only what is between SELECT and FROM.

Nice so I have found this answer that propose this regex: (?<=SELECT)(.*)(?=FROM). It's perfect if lookbehind works in JavaScript, according to this post:

Unlike lookaheads, JavaScript doesn't support regex lookbehind syntax

So it won't work(test it in regexpal that is made for JS). This anwser proposes this regex: 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...

SELECT a, b, c, d FROM

into this...

SELECT Count(*) FROM

Thank you in advance.

4

5 回答 5

5

只需使用捕获组:

"SELECT a, b, c, d FROM".replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)")
于 2013-08-22T19:08:56.553 回答
2

尝试这个:-

$("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)
});

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

于 2013-08-22T19:07:05.050 回答
1

就像此特定字符串的正则表达式的替代方法一样:

str = 'SELECT COUNT(*) ' + str.substr(str.indexOf('FROM'));
于 2013-08-22T19:08:02.373 回答
1

没有正则表达式

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);
}
于 2013-08-22T19:13:37.337 回答
1

好吧,您可以SELECT像我在评论中所说的那样放回后面:

str.replace(/SELECT (.*?)(?= FROM)/i, "SELECT Count(*)");
于 2013-08-22T19:05:23.333 回答