Pavan Kumar Jayini
Pavan Kumar Jayini

Reputation: 1

regex to get two different words from a string in java

I will be getting the string as app1(down) and app2(up) the words in the brackets indicate status of the app, they may be up or down depending,

now i need to use a regex to get the status of the apps like a comma seperated string

ex:ill get app1(UP) and app2(DOWN) required result UP,DOWN

Upvotes: 0

Views: 91

Answers (4)

Divyesh Kanzariya
Divyesh Kanzariya

Reputation: 3789

It's easy using RegEx like this:

\\((.*?)\\)

Regular expression visualization

String x = "app1(UP) and app2(DOWN)";
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x);
String tmp = "";
while(m.find()) {
    tmp+=(m.group(1))+",";
}

System.out.println(tmp);

Output:

UP,DOWN,

Java 8: using StringJoiner

String x = "app1(UP) and app2(DOWN)";
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x);
StringJoiner sj = new StringJoiner(",");

while(m.find()) {
    sj.add((m.group(1)));
}

System.out.print(sj.toString());

Output:

UP,DOWN

(Last , is removed)

Upvotes: 2

Cromax
Cromax

Reputation: 2042

Consider this code:

    private static final Pattern RX_MATCH_APP_STATUS = Pattern.compile("\\s*(?<name>[^(\\s]+)\\((?<status>[^(\\s]+)\\)");
    final String input = "app1(UP) or app2(down) let's have also app-3(DOWN)";
    final Matcher m = RX_MATCH_APP_STATUS.matcher(input);
    while (m.find()) {
        final String name = m.group("name");
        final String status = m.group("status");
        System.out.printf("%s:%s\n", name, status);
    }

This plucks from input line as many app status entries, as they really are there, and put each app name and its status into proper variable. It's then up to you, how you want to handle them (print or whatever).

Plus, this gives you advantage if there will come other states than UP and DOWN (like UNKNOWN) and this will still work.

Minus, if there are sentences in brackets prefixed with some name, that is actually not a name of an app and the content of the brackets is not an app state.

Upvotes: 0

ZiTAL
ZiTAL

Reputation: 3581

import java.util.ArrayList;
import java.util.List;
import java.util.regex.*;

public class ValidateDemo
{
        public static void main(String[] args)
        {
                String input = "ill get app1(UP) and app2(DOWN)";
                Pattern p = Pattern.compile("app[0-9]+\\(([A-Z]+)\\)");
                Matcher m = p.matcher(input);


                List<String> found = new ArrayList<String>();
                while (m.find())
                {
                        found.add(m.group(1));
                }

                System.out.println(found.toString());
        }
}

my first java script, have mercy

Upvotes: 0

Rakesh
Rakesh

Reputation: 109

Use this as regex and test it on http://regexr.com/ [UP]|[DOWN]

Upvotes: -1

Related Questions