java笔试之参数解析(正则匹配)

在命令行输入如下命令:

xcopy /s c: d:,

各个参数如下: 

参数1:命令字xcopy 

参数2:字符串/s

参数3:字符串c:

参数4: 字符串d:

请编写一个参数解析程序,实现将命令行各个参数解析出来。

解析规则: 

1.参数分隔符为空格 
2.对于用“”包含起来的参数,如果中间有空格,不能解析为多个参数。比如在命令行输入xcopy /s “C:program files” “d:”时,参数仍然是4个,第3个参数应该是字符串C:program files,而不是C:program,注意输出参数时,需要将“”去掉,引号不存在嵌套情况。
3.参数不定长 
4.输入由用例保证,不会出现不符合要求的输入 

链接:https://www.nowcoder.com/questionTerminal/668603dc307e4ef4bb07bcd0615ea677
来源:牛客网

输入描述:

输入一行字符串,可以有空格



输出描述:

输出参数个数,分解后的参数,每个参数都独占一行

输入例子:
xcopy /s c:\ d:\
输出例子:
4
xcopy
/s
c:\
d:\

package test;

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


//使用正则表达式
public class exam19 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // result存储经过正则表达式判定后的字符串
        ArrayList<String> result = new ArrayList<String>();
        String reg = "(".*?")|([a-zA-Z_0-9:/\\]+)";// *?非贪婪匹配,最少重复;/\\来匹配\
        Pattern pattern = Pattern.compile(reg);
        while (scanner.hasNext()) {
            String string = scanner.nextLine();
            // 获取matcher对象
            Matcher matcher = pattern.matcher(string);
            String tokeString = "";
            int pos = 0;
            while (pos < string.length()) {
                //匹配定位:开始到结束
                matcher.region(pos, string.length());
                if (matcher.lookingAt()) {
                    // group(0)表示整个串;
                    // group(1)只符合第一个括号的匹配;
                    // group(2)只符合第二个括号匹配
                    if (matcher.group(1) != null) {
                        result.add(matcher.group(1).replaceAll(""", ""));
                    } else if (matcher.group(2) != null) {
                        result.add(matcher.group(2));
                    }
                    pos = matcher.end();//总匹配的最后索引
                } else {
                    pos++;
                }

            }
            System.out.println(result.size());
            for (String tok : result) {
                System.out.println(tok);
            }
        }
        scanner.close();
    }
}
原文地址:https://www.cnblogs.com/bella-young/p/6423914.html