简体   繁体   English

如何使用扫描仪基于正则表达式将值分配给多个变量

[英]How to use Scanner to assign value to multiple variables based on regex

I am getting input from console using Scanner. 我正在使用扫描仪从控制台获取输入。 Expected input format is CR127-0772. 预期的输入格式为CR127-0772。 I would like to extract 3 different values from that input: first one is string 'CR', second one is 127 and third one is 0072. This can be performed in C using scanf 我想从该输入中提取3个不同的值:第一个是字符串'CR',第二个是127,第三个是0072。这可以在C中使用scanf执行

scanf("%s%d-%d", &st, &a, &b)

How can I do same task using java? 如何使用Java执行相同的任务? I don't see how I can use regex with Scanner. 我看不到如何在Scanner中使用正则表达式。 Your help is much appreciated. 非常感谢您的帮助。

You can just scan it to a string, then set the variables to substrings of that string (parsed for ints as necessary). 您可以将其扫描为一个字符串,然后将变量设置为该字符串的子字符串(根据需要解析为ints)。

String s = scanner.nextLine();
String st = s.substring(0,2);
int a = Integer.parseInt(s.substring(2,5));
int b = Integer.parseInt(s.substring(6));

This does assume that the string is always two characters and the first int is always three digits. 这确实假定字符串始终是两个字符,而第一个int始终是三位数。 The second int can be arbitrarily long. 第二个int可以任意长。

Firstly, Java couldn't do it, because java doesn't use pointers. 首先,Java 无法做到这一点,因为Java不使用指针。 The best you could hope for is a method that returns a list/array of values. 您可能希望的最好的方法是返回值的列表/数组。

Secondly, "no"; 其次,“不”; there's nothing similar in the JDK that does this kind of thing. JDK中没有类似的东西可以做这种事情。

However, you can do it fairly simply in as many lines of code as you have variables: 但是,您可以在具有变量的任意多行代码中相当简单地完成此操作:

String input = "CR127-0772"; // given this got from console

String st = input.replaceAll("\\d.*", ""); // delete from 1st digit onwards
String a = input.replaceAll("^\\D+|-.*", ""); // delete leading non-digits or dash onwards
String b = input.replaceAll(".*-", ""); // delete everything up to a dash

This uses regex to match what you don't want and "delete" it by replacing with a blank. 这使用正则表达式来匹配您不需要的内容,并通过替换为空白来“删除”它。

That's not possible using Scanner since this class works with a single delimiter. 使用Scanner是不可能的,因为此类使用单个定界符。 What you should do here is manually parse the String with a desired format. 您在这里应该做的是手动解析具有所需格式的String

Here's an example of how to do this: 这是如何执行此操作的示例:

String data = scanner.nextLine();
String stringPart = data.replaceAll("[^a-zA-Z]", ""); //remove all non letter chars
int[] numbers = Arrays.stream( //convert to Stream the result of
    data.replaceAll("[a-zA-Z]", "") // remove all letter chars
        .split("-")                 // and split by "-"
    ).mapToInt(Integer::parseInt) //map the array of String to a stream of int (not Integer)
    .toArray(); //convert the stream into an array int[]

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

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