How to build the regex to find particular word

Viewed 108

I need to find and print out a particular word in a String. What regex can you recommend me to find a "9.1.1_offline" in following String:

EGA_SAMPLE_APP-iOS-master-<Any word>-200710140849862

Another examples are:

  • EGA_SAMPLE_APP-iOS-master-9.2.3_online-200710140849862
  • EGA_SAMPLE_APP-iOS-master-10.2.3_offline-200710140849862
2 Answers

I can suggest the following one line option using String#replaceAll:

String input = "EGA_SAMPLE_APP-iOS-master-9.2.3_online-200710140849862";
String target = input.replaceAll(".*\\b(\\d+\\.\\d+\\.\\d+_(?:online|offline))\\b.*", "$1");
System.out.println(target);

This prints:

9.2.3_online

Use the regex, \\d+\\.\\d+\\.\\d+\\_(offline|online)

Demo:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Test strings
        String[] arr = { "EGA_SAMPLE_APP-iOS-master-9.1.1_offline-200710140849862",
                "EGA_SAMPLE_APP-iOS-master-9.2.3_online-200710140849862",
                "EGA_SAMPLE_APP-iOS-master-10.2.3_offline-200710140849862" };
        Pattern pattern = Pattern.compile("\\d+\\.\\d+\\.\\d+\\_(offline|online)");

        // Print the matching string
        for (String s : arr) {
            Matcher matcher = pattern.matcher(s);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
}

Output:

9.1.1_offline
9.2.3_online
10.2.3_offline

Explanation of the regex:

  1. \\d+ specifies one or more digits
  2. \\. specifies a .
  3. \\_ specifies a _
  4. (offline|online) specifies offline or online.

[Update]

Based on the edited question i.e. find anything between EGA_SAMPLE_APP-iOS-master- and -An_integer_number: Use the regex, EGA_SAMPLE_APP-iOS-master-(.*)-\\d+

Demo:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Test strings
        String[] arr = { "EGA_SAMPLE_APP-iOS-master-9.1.1_offline-200710140849862",
                "EGA_SAMPLE_APP-iOS-master-9.2.3_online-200710140849862",
                "EGA_SAMPLE_APP-iOS-master-10.2.3_offline-200710140849862",
                "EGA_SAMPLE_APP-iOS-master-anything here-200710140849862" };

        // Define regex pattern
        Pattern pattern = Pattern.compile("EGA_SAMPLE_APP-iOS-master-(.*)-\\d+");

        // Print the matching string
        for (String s : arr) {
            Matcher matcher = pattern.matcher(s);
            while (matcher.find()) {
                System.out.println(matcher.group(1));
            }
        }
    }
}

Output:

9.1.1_offline
9.2.3_online
10.2.3_offline
anything here

Explanation of the regex:

.* specifies anything and the parenthesis around it specifies a capturing group which I've captured with group(1) in the code.

Related