简体   繁体   English

在java中使用正则表达式解析字符串

[英]Parse a string using Regular Expression in java

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.我有一个内容 text:text,我想从一个包含 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}

Try this pattern试试这个模式

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

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

如果你有像"key1:value1 key2:value2..."这样的字符串,那么你可以使用这个正则表达式:

([^ ]*:[^ ]*)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM