changed
changed

Reputation: 2143

java regular expression

I have a string like this

STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01|

and i want to extract values of few of the keys here.

like whats the value of PNAM and SSTA.

I want a regular expression that can provide the values of few of the keys and keys can be in any order.

Upvotes: 0

Views: 123

Answers (3)

Kevin
Kevin

Reputation: 5694

Would something like this work for you?

String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01";
String[] parts = str.split("\\|");

for (String part : parts)
{
    String[] nameValue = part.split("=");

    if (nameValue[0] == "somekey")
    {
        // ..
    }
}

Upvotes: 3

Reverend Gonzo
Reverend Gonzo

Reputation: 40811

So, the way your problem is really isn't best solved with regular expressions. Instead, use split() like someone else has offered, but instead of having a crazy if loop, load everything into a map.

String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01";
String[] parts = str.split("|");
Map<String, String> properties = new HashMap<String, String>();

for (String part : parts) {
    String[] nameValue = part.split("=");
    properties.put(nameValue[0], nameValue[1]);
}

Then all you have to do is, properties.get("PNUM")

Upvotes: 2

anubhava
anubhava

Reputation: 784888

Use this Java code:

String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01|";
Pattern p = Pattern.compile("([^=]*)=([^|]*)\\|");
Matcher m = p.matcher(str);
String pnamVal = null, sstaVal = null;
while (m.find()) {
    //System.out.println("Matched: " + m.group(1) + '=' + m.group(2));
    if (m.group(1).equals("PNAM"))
        pnamVal = m.group(2);
    else if (m.group(1).equals("SSTA"))
        sstaVal = m.group(2);

    if (pnamVal != null && sstaVal != null)
       break;
}
System.out.println("SSTA: " + sstaVal);
System.out.println("PNAM: " + pnamVal);

OUTPUT

SSTA: 20110209 00:01:01
PNAM: test_.xml

Upvotes: 1

Related Questions