Java正则表达式用于解析带引号的参数

3
需要一个Java正则表达式模式来处理以下情况:
案例1: 输入字符串:
"a"

匹配:

a

Case 2:
输入字符串:
"a b"

匹配:

a b

"案例3:"
"输入字符串:"
"aA Bb" cCc 123 4 5 6 7xy "\"z9" "\"z9$^"

匹配结果:

aA Bb
cCc
123
4
5
6
7xy
"z9
"z9$^

Case 4:

Input string:

"a b c

匹配:

None - since the quotes are unbalanced, hence pattern match fails.

Case 5:

Input string:

"a b" "c

匹配项:

None - since the quotes are unbalanced, hence pattern match fails.

Case 6:
输入字符串:
"a b" p q r "x y z"

匹配:

a b
p 
q 
r
x y z

第七种情况:

输入字符串:

"a b" p q r "x y \"z\""

匹配:

a b
p 
q
r
x y "z"

案例8:

输入字符串:

"a b" p q r "x \"y \"z\""

匹配:

a b
p 
q 
r
x "y "z"

当然,最简单的一个案例:
第9个案例:
输入字符串:
a b

匹配:

a
b

尝试使用了一个模式,但似乎不能匹配所有上述情况。
public List<String> parseArgs(String argStr) {
    List<String> params = new ArrayList<String>();
    String pattern = "\\s*(\"[^\"]+\"|[^\\s\"]+)";
    Pattern quotedParamPattern = Pattern.compile(pattern);
    Matcher matcher = quotedParamPattern.matcher(argStr);
    while (matcher.find()) {
        String param = matcher.group();
            System.out.println(param);
            params.add(param);
    }
    return params;
}

public void test(String argStr) {
    String[] testStrings = new String[]{"a", "a b", "a b \"c\"", "a b \"c"};
    for(String s: testStrings){
        parseArgs(s);
    }
}

1
可以解决,但你需要展示一些解决的努力。至少将所有的示例输入字符串放入一个字符串数组(String[])中,并将Java代码放在这里。 - anubhava
@anubhava 添加了Java代码和一些输入字符串。 - Amith Koujalgi
我猜你实际的字符串不仅仅是单个小写字母。它们是否需要包含大写字母、数字、特殊字符等?它们的长度是否有限制? - CAustin
@CAustin 可能会有大写字母、数字、特殊字符等,但并没有限制。 - Amith Koujalgi
我不确定你想要什么,但我确定答案早在你到达之前就已经存在了。 - Pedro Lobito
@Tuga 我正在构建一个命令行应用框架,需要解释一个命令及其参数。这个工作基本上是从给定的命令字符串中解析出每个有效的参数。 - Amith Koujalgi
4个回答

2

我写了一个名为"CLIParser"的类,它可以帮助你获得结果。

//instantiate the CLIParser 

CLIParser parser = new CLIParser("\"a b\" p q r \"x y z\"");

//call the method getTokens which gives you the result.

ArrayList<String> resultTokens = parser.getTokens();


###################CLI Parser Class definition#################################

class CLIParser {
    private String cmdString;

    public CLIParser(String cmdString) {
        this.cmdString = cmdString;
    }

    public ArrayList<String> getTokens() throws Exception {
        ArrayList<String> finalTokens = new ArrayList<String>();
        ArrayList<StringBuffer> tokens = new ArrayList<StringBuffer>();
    char inArray[] = this.cmdString.toCharArray();
    StringBuffer token = new StringBuffer();
    int valid = checkIfTheStringIsValid(inArray);
    if (valid == -1) {
        for (int i = 0; i <= inArray.length; i++) {

            if (i != inArray.length) {
                if ((inArray[i] != ' ') && (inArray[i] != '"')) {
                    token.append(inArray[i]);
                }

                if ((inArray[i] == '"') && (inArray[i - 1] != '\\')) {
                    i = i + 1;
                    while (checkIfLastQuote(inArray, i)) {
                        token.append(inArray[i]);
                        i++;
                    }
                }
            }
            if (i == inArray.length) {
                tokens.add(token);
                token = new StringBuffer();
            } else if (inArray[i] == ' ' && inArray[i] != '"') {
                tokens.add(token);
                token = new StringBuffer();
            }
        }
    } else {
        throw new InvalidCommandException(
                "Invalid command. Couldn't identify sequence at position "
                        + valid);
    }
    for(StringBuffer tok:tokens){
        finalTokens.add(tok.toString());
    }
    return finalTokens;
}

private static int checkIfTheStringIsValid(char[] inArray) {
    Stack myStack = new Stack<Character>();
    int pos = 0;
    for (int i = 0; i < inArray.length; i++) {
        if (inArray[i] == '"' && inArray[i - 1] != '\\') {
            pos = i;
            if (myStack.isEmpty())
                myStack.push(inArray[i]);
            else
                myStack.pop();
        }
    }
    if (myStack.isEmpty())
        return -1;
    else
        return pos;
}

private static boolean checkIfLastQuote(char inArray[], int i) {
    if (inArray[i] == '"') {
        if (inArray[i - 1] == '\\') {
            return true;
        } else
            return false;
    } else
        return true;
}
}

2

我不知道用正则表达式直接解决的方法。

但是你可以用一些独特的关键词替换内部转义序列,然后就可以使用正则表达式匹配你的字符串了。

String[] testStrings = new String[]{
         "a", "a b", "a b \"c\"", "a b \"c", "\"a b\" p q r \"x y z\""};
Pattern parsingPattern = Pattern.compile("(\".*?\")|( [^ ^\"]+)");
for(String s: testStrings) {
   s=s.replace("(?<!\\)\\"","@@@");
}
for(String s: testStrings) {
    List<String> params = null;
    int count = StringUtils.countMatches(s, "\"");
    if(count%2==0){
    params = new ArrayList<String>();
    Matcher matcher = parsePattern.matcher(s); 
    while (matcher.find())
        params.add( matcher.group(1) != null ? matcher.group(1) : matcher.group(2));
   }
}

一旦您获取匹配项,您可以使用实际关键字替换您的唯一标识符。

我尚未测试代码片段,但希望您可以进行一些微小的调整以使其正常工作。


看起来是一个公平的解决方案。谢谢! - Amith Koujalgi

0

为了让你开始,你可以使用这个基于Java正则表达式的代码:

public List<String> parseArgs(String argStr, Pattern validPattern, Pattern parsePattern) {
    List<String> params = null;
    if (validPattern.matcher(argStr).matches()) {
        params = new ArrayList<String>();
        Matcher matcher = parsePattern.matcher(argStr); 
        while (matcher.find())
            params.add( matcher.group(1) != null ? matcher.group(1) : matcher.group(2));
    }
    return params;
}

public void parseIt() {
    Pattern validatePattern = Pattern.compile("^(?=(?:(?:[^\"]*\"){2})*[^\"]*$).*$");
    Pattern parsingPattern = Pattern.compile("\"([^\"]*)\"|(\\w+)");

    String[] testStrings = new String[]{
             "a", "a b", "a b \"c\"", "a b \"c", "\"a b\" p q r \"x y z\""};
    for(String s: testStrings) {
        List<String> parsedList = parseArgs(s, validatePattern, parsingPattern);
        System.out.printf("input: %-30s :: parsed: %s%n", s, parsedList);
    }
}

输出:

input: a                              :: parsed: [a]
input: a b                            :: parsed: [a, b]
input: a b "c"                        :: parsed: [a, b, c]
input: a b "c                         :: parsed: null
input: "a b" p q r "x y z"            :: parsed: [a b, p, q, r, x y z]

提示:虽然我已经注意到你最近添加了嵌套引用,但是这个答案仍需要进行增强。


这似乎适用于大多数情况。但我正在尝试提取其中包含转义引号的字符串。尝试了这个:"aA Bb" cCc 123 4 5 6 7xy ""z9" ""z9$^" 这应该给我第8个参数为"z9",第9个参数为"z9$^"。谢谢。 - Amith Koujalgi
以上情况的正则表达式是什么? - Amith Koujalgi
实际上,转义没有尽头。即使反斜杠也可以被转义。你是如何获取这个输入的? - anubhava
是的,没错。这就是我正在构建的应用程序应该工作的方式。即使是这个也是有效的 "aA Bb" cCc 123 4 5 6 7xy ""\z9" ""z9$^"。而且这些字符串是从标准输入读取的。 - Amith Koujalgi
但是正则表达式难道不比解析器更强大吗?因为对我来说,解析似乎是一项有些昂贵的操作,因为会同时发出大量带有众多参数的命令。 - Amith Koujalgi
显示剩余3条评论

0

试试这个:

("\S+?(?: \S+?)*"|\S+?)

在这里看到它的效果:http://regex101.com/r/fA5hN0

只需运行全局匹配并返回\1。每个被返回的捕获组都应该包含你想要的内容。


是否有可用的Java正则表达式字符串,因为上面的模式需要转义斜杠和引号,即使转义了,对于所有情况似乎也无法工作。尝试了这个输入字符串:"a b" p q r "x y "z"" - Amith Koujalgi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接