简体   繁体   中英

Extract Text from multi-line string

I've one string MYSTRING with multiple lines as below:

X:String1;;;; X1:String2 X2:String3 YY1:String4

My target is to extract each string from the above string. I found below formula:

Pattern pattern = Pattern.compile("([\\n|;|:](X:|X1:)[0-9a-zA-Z-\\säöüÄÖÜß,]*[\\n|;])");
Matcher m = pattern.matcher(MYSTRING);

if(m.find())  {
    String  name = m.group(1).substring(1);
}

With the above forumla I succeeded to get String1 only. how to get rest of String2, String3, .....?

I managed to solve this by double matching queries as below:

First perform the query for X

pattern = Pattern.compile("([\\n|;|:](X:)[0-9a-zA-Z-\\säöüÄÖÜß,]*[\\n|;])");
            m = pattern.matcher(MYSTRING);

        if(m.find())  {
            String  string1 = m.group(1).substring(1);
        }

Then perform the query for X1:

pattern = Pattern.compile("([\\n|;|:](X1:)[0-9a-zA-Z-\\säöüÄÖÜß,]*[\\n|;])");
            Matcher m = pattern.matcher(MYSTRING);

        if(m.find())  {
            String  string2 = m.group(1).substring(1);
        }

This is not the right way specially if you have lot of fields, but at least it working for me just do query two times only, can be considered as temp sol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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