1

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];
3
  • 2
    Couldn't you use indexOf and substring ? Commented Mar 1, 2016 at 17:14
  • 1
    why don't you just get the index of FROM and take substring then? Commented Mar 1, 2016 at 17:14
  • Try this regex101.com/r/nM2hE9/2 Commented Mar 1, 2016 at 17:41

3 Answers 3

2

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just used solution 1
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.