2

I am trying to parse a String using Regular expression. I have a content text:text and I want to parse the content from a string which has text:text. Code:

String lines=" from:cal_date_d type:string relationship:many_to_one sql_on:${fact_customer.dw_update_date} = ${cal_date_d.dw_update_date}";
Pattern p = Pattern.compile("(\"?[\\w ]*)\\:(\"?([\\w]*)\"?)");
                Matcher m = p.matcher(lines);
                while(m.find()) {
                    String Column_Data=m.group(0);
                    System.out.println("Regex:           "+Column_Data);
                }

Ouput:

   from:cal_date_d
type:string
relationship:many_to_one
sql_on:

Expected Output:

from:cal_date_d 
type:string 
relationship:many_to_one 
sql_on:${fact_customer.dw_update_date} = ${cal_date_d.dw_update_date}
2
  • The first problem is that the value can contain not only word characters, but also the dollar sign, braces, the equals sign, periods, and spaces. The larger problem is that spaces normally separate key:value pairs, but can be contained within the sql_on value. What is the syntax of sql_on? Will it always have a close brace and an equals sign before the internal spaces? Will sql_on always appear, and appear last? You need some other aspect of it like that to base this on, or adopt a different approach. Commented Jan 6, 2017 at 6:12
  • for Sql_on key, the pattern is same and default all the time Commented Jan 6, 2017 at 6:16

2 Answers 2

2

Try this pattern

([^\s]+( ?= ?[^\s]*)?)

https://regex101.com/r/c0q4W0/2

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks ,It worked . But I am getting extra empty string along with. But that will be fine, I can parse that by checking the string length.
@Navyah Maybe change it to require one or more (+) instead of zero or more (*) characters.
@DavidConrad That's correct. It was a typo. Now changed
0

If you have string like "key1:value1 key2:value2..." then you can use this regex:

([^ ]*:[^ ]*)

3 Comments

But OP doesn't have a string like that, since the last value contains spaces (around the equals sign).
Oh, I see. In this case it is not possible to parse because space it is delimiter between key-value pairs and last pair has space around "=" as you mentioned.
@Dmitry, Using the below Pattern. I am getting the result as below from:cal_date_d type:string relationship:many_to_one sql_on:${fact_customer.dw_update_date}

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.