Reputation: 395
I am trying to extract a set of strings from a consul output. What I want to do is remove all instances of the strings which start with
/usr/lib/ocf/resource.d/
Input String
-rwxr-xr-x. 1 root root 971 Sep 22 13:15 /usr/lib/ocf/resource.d/cloud_init_ocf.sh/n-rwxr-xr-x. 1 root root 662 Aug 28 11:25 /usr/lib/ocf/resource.d/credentialmanagercliRestartVM.sh/n-rwxr-xr-x. 1 root root 843 Sep 28 11:13 /usr/lib/ocf/resource.d/jboss_healthcheck.sh
In the above example string that would be the strings of
/usr/lib/ocf/resource.d/cloud_init_ocf.sh
/usr/lib/ocf/resource.d/credentialmanagercliRestartVM.sh
/usr/lib/ocf/resource.d/jboss_healthcheck.sh
What I have tried
I have tried to match the Strings which start with
\\b/usr/lib/ocf/resource.d/.*\\b
I got from here
Code
regexChecker("\\b/usr/lib/ocf/resource.d/.*\\b", output);
private ArrayList<String> regexChecker(String regEx, String str2Check) {
final ArrayList<String> result = new ArrayList<>();
Pattern checkRegex = Pattern.compile(regEx);
Matcher regexMatcher = checkRegex.matcher(str2Check);
String regexMatch;
while (regexMatcher.find()) {
if (regexMatcher.group().length() != 0) {
regexMatch = regexMatcher.group();
result.add(regexMatch);
}
}
return result;
}
I think the issue is the /n
character which is inserted at the end of each line.
Upvotes: 0
Views: 491
Reputation: 1320
try this way
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main{
public static void main(String[] args) {
String regex = "(\\/usr\\/lib\\/ocf\\/resource\\.d\\/[a-zA-Z_]*(\\.sh[\\s|]?)?)";
String string = "-rwxr-xr-x. 1 root root 971 Sep 22 13:15 /usr/lib/ocf/resource.d/cloud_init_ocf.sh/n-rwxr-xr-x. 1 root root 662 Aug 28 11:25 /usr/lib/ocf/resource.d/credentialmanagercliRestartVM.sh/n-rwxr-xr-x. 1 root root 843 Sep 28 11:13 /usr/lib/ocf/resource.d/jboss_healthcheck.sh";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
int i =1;
while (matcher.find()) {
System.out.println("Group " + i++ + ": " + matcher.group(0));
}
}
}
and output is
Group 1: /usr/lib/ocf/resource.d/cloud_init_ocf.sh
Group 2: /usr/lib/ocf/resource.d/credentialmanagercliRestartVM.sh
Group 3: /usr/lib/ocf/resource.d/jboss_healthcheck.sh
Upvotes: 2