java正则表达式解析

时间:2018-04-26 09:29:53

标签: java regex parsing

感谢您查看我的问题。

此处用户输入格式为“xD xS xP xH”的字符串。程序获取字符串,将其拆分在空格键上,然后使用正则表达式来解析字符串。我的“最终字符串正则表达式”存在问题,我不知道在哪里。

final String regex = "([0-9]+)[D|d]| ([0-9]+)[S|s]| ([0-9]+)[P|p]| ([0-9]+)[H|h]";

最后,循环只打印出D的值,所以我怀疑它会移动到匹配S或s的错误。

public class parseStack
{
   public parseStack()
   {
      System.out.print('\u000c');
      String CurrencyFormat = "xD xS xP xH";
      System.out.println("Please enter currency in the following format: \""+CurrencyFormat+"\" where x is any integer");

       Scanner scan = new Scanner(System.in);
       String currencyIn = scan.nextLine();
       currencyFinal = currencyIn.toUpperCase();
       System.out.println("This is the currency you entered: "+currencyFinal);

       String[] tokens = currencyFinal.split(" ");
       final String input = tokens[0];
       final String regex = "([0-9]+)[D|d]| ([0-9]+)[S|s]| ([0-9]+)[P|p]| ([0-9]+)[H|h]";

       if (input.matches(regex) == false) {
           throw new IllegalArgumentException("Input is malformed.");            
       }

        long[] values = Arrays.stream(input.replaceAll(regex, "$1 $2 $3 $4").split(" "))
                .mapToLong(Long::parseLong)
                .toArray();

      for (int i=0; i<values.length; i++)
      {
        System.out.println("value of i: "+i+ "    |" +values[i]+ "|");
      }

    //pause to print
    System.out.println("Please press enter to continue . . . ");
    Scanner itScan = new Scanner(System.in);
    String nextIt = itScan.nextLine();    
 }
}

3 个答案:

答案 0 :(得分:0)

您的正则表达式应为[\d]+[DdSsPpHh]

您遇到的问题是将字符串拆分为块,然后将块与匹配原始字符串的RegEx匹配。

HOWEVER 此答案仅解决代码中的问题。您的日常工作似乎并不能满足您的期望。你的期望根本不明确。

修改

添加了多位数要求。

答案 1 :(得分:0)

你的正则表达式可以有所简化。

"(?i)(\d+d) (\d+s) (\d+p) (\d+h)"

将对多个数字(\ d +)

进行不区分大小写的匹配

这可以进一步简化为

"(?i)(\d+[dsph])"

将迭代匹配货币字符串中的各个组。

答案 2 :(得分:0)

首先,你的正则表达式看起来有点复杂。您输入的格式是&#34; xD xS xP xH&#34; 您也将输入转换为大写currencyIn = currencyIn.toUpperCase();,但这不是问题所在。

问题是

String[] tokens = currencyIn.split(" ");
final String input = tokens[0];

您正在拆分输入,只使用第一部分&#34; xD&#34;

固定代码如下:

String currencyIn = scan.nextLine();
currencyIn = currencyIn.toUpperCase();
System.out.println("This is the currency you entered: "+currencyIn);

final String regex = "([0-9]+)D ([0-9]+)S ([0-9]+)P ([0-9]+)H";

if (!currencyIn.matches(regex)) {
    throw new IllegalArgumentException("Input is malformed.");
}

long[] values = Arrays.stream(currencyIn.replaceAll(regex, "$1 $2 $3 $4").split(" "))
    .mapToLong(Long::parseLong)
    .toArray();

for (int i=0; i<values.length; i++) {
    System.out.println("value of i: "+i+ "    |" +values[i]+ "|");
}