我无法弄清楚如何从字符串中的已知位置找到以前的空白区域。
例如:这是一个sql语句,我需要在使用.*
时找到tableName。 Finidng表别名很容易,因为我可以从a。*获得它。但我需要实际的表名。
"select a.*, a.id , distinct b.id as newID, a.name, test as columnName, b.* from table1name a inner join table2name b on a.id = b.id"
因此,使用一堆indexof(" " + tableAlias + " ")
我可以找出表名结束的位置,但我不知道长度或起始位置。我需要的是在我的indexof返回的点之前找到空格。
所以上面例子中的indexof在查找标识实际表名结尾的15
时产生" " + tableAlias + " "
,所以我可以假设tableName以索引14
结束并且只是开始在14之前的空格之后(当然假设表名中没有空格......
任何想法?
答案 0 :(得分:0)
你可以迭代字符串并尝试找到一个空格
// 0 28 35
var str = "select a, b, distinct c from myTable where a < 5";
var i = 35; // position of the end of myTable (you already calculated it)
for(;i >= 0; i--){
if(str.charAt(i) == ' ') {
break;
}
}
// now i marks the index of the whitespace before myTable (in the example it would be 28)
答案 1 :(得分:0)
感谢所有在此贡献的人。 string.lastIndex就是答案。我认为这个函数返回了给定字符串的最终索引,但事实证明它给出了前一个实例,所以它正是我所需要的。