Reputation: 141
I have a string that I need to split
SELECT a, b, c FROM X....
I need to split it and only keep, "FROM...." and onwards. Right now I have this, but I think it will actually get rid of the FROM string also correct?
String query = xyz.getQuery();
String [] newQuery = query.split("FROM");
String splitQuery = newQuery[1];
Upvotes: 1
Views: 1419
Reputation: 1293
In addition with split and possitive lookahead, so you don't get rid of "FROM".
@Test
public void testRegex(){
String query = "SELECT a, b, c FROM x y z";
String regex = "(?=FROM.*)|(?=from.*)";
System.out.println(query.split(regex)[1]);
assertEquals("FROM x y z", query.split(regex)[1]);
}
FROM x y z
Upvotes: 0
Reputation: 11032
Why exactly do you need regex
for this?
without regex
Sol 1
Add this to your code
String splitQuery = "FROM " + newQuery[1];
Sol 2
System.out.println(line.substring(line.indexOf("FROM")));
and if you still need regex
String line = "SELECT a, b, c FROM X....";
String pattern = "((FROM|from).*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
}
Upvotes: 2
Reputation: 3703
Instead of splitting, you could try this. Assuming you only want what is written after the first FROM
and not from any nested FROM
:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public String getSubString(String s)
{
Pattern p = Pattern.compile("FROM.+");
Matcher m = p.matcher(s);
if(m.find())
{
return m.group(0);
}
return null;
}
public static void main(String[] args) {
String query = "SELECT a, b, c FROM myTable";
Solution sol = new Solution();
String ans = sol.getSubString(query);
if(ans != null)
{
System.out.println(ans);
}
else
{
System.out.println("Not Found");
}
}
}
Aside from this a better way is to first get the starting position of FROM
and then simply use substring
method from that point to length of the string.
Upvotes: 0