简体   繁体   English

正则表达式以匹配字符串的多个实例

[英]Regex to match multiple instances of a string

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 我试图匹配以\\\\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. 我认为问题是在每行末尾插入的/n字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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