簡體   English   中英

正則表達式以匹配字符串的多個實例

[英]Regex to match multiple instances of a string

我正在嘗試從領事輸出中提取一組字符串。 我要做的是刪除所有以開頭的字符串實例

/usr/lib/ocf/resource.d/

輸入字符串

-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

在上面的示例字符串中,將是

/usr/lib/ocf/resource.d/cloud_init_ocf.sh
/usr/lib/ocf/resource.d/credentialmanagercliRestartVM.sh
/usr/lib/ocf/resource.d/jboss_healthcheck.sh

我嘗試過的

我試圖匹配以\\\\b/usr/lib/ocf/resource.d/.*\\\\b開頭的字符串
我從這里來的

 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;
    }

我認為問題是在每行末尾插入的/n字符。

嘗試這種方式

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));
        }
    }
}

和輸出是

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