java 使用 Scanner 类解析字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12032669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:21:05  来源:igfitidea点击:

Parsing string using the Scanner class

javaregex

提问by FirmView

I am trying to parse some lines and check their values, For example in the string:

我正在尝试解析一些行并检查它们的值,例如在字符串中:

   " 1 ON OFF";

I have to check whether:

我必须检查是否:

  • the first character is blank.
  • the second character is int.
  • the third character is blank.
  • the fourth character is 2 characters and it is ON.
  • the fifth character is blank.
  • the sixth character is 3 characters and it is OFF.
  • 第一个字符为空。
  • 第二个字符是 int。
  • 第三个字符为空。
  • 第四个字符是 2 个字符,它是 ON。
  • 第五个字符为空。
  • 第六个字符是 3 个字符,它是 OFF。

I can do this at one go using regex, but what I want is that after each check I have to display whether is correct or not like:

我可以使用正则表达式一次性完成此操作,但我想要的是每次检查后我都必须显示是否正确,例如:

   System.out.println("1st character is not a blank : incorrect");
   System.out.println("1st character is blank : correct");

I thought of using Scannerclass for this, but when I try to detect the first character, it is showing 1instead of blank for the string,

我想Scanner为此使用类,但是当我尝试检测第一个字符时,它显示1字符串而不是空白,

   " 1 ON OFF";

   public class NewClass {    

    public void StringExample(){
        String str = " 1 ON OFF";

        Scanner sc = new Scanner(str);
        System.out.println(sc.next());
    }

    public static void main(String args[]){
        NewClass nc = new NewClass();
        nc.StringExample();
    }
}

Is there any other class in java with which this can be done easily?

java中是否还有其他类可以轻松完成此操作?

回答by nhahtdh

The closest I can think of is splitting by word boundary:

我能想到的最接近的是按词边界拆分:

String tokens[] = " 1 ON OFF".split("\b");

It will give the following array:

它将给出以下数组:

{ " ", "1", " ", "ON", " ", "OFF" }

It fits your ordering and your definition of 1st-6th "character".

它适合您的订购和您对第 1-6 个“字符”的定义。

回答by Mark Elliot

It's worth taking a look at StringReader, which will let you scan through the string character by character. Another option is simply to read each character (String#charAt) and check if it meets your rules.

StringReader 值得一看,它可以让您逐个字符地扫描字符串。另一种选择是简单地读取每个字符 (String#charAt) 并检查它是否符合您的规则。

回答by Mark Elliot

You can use parboiledand declare a small grammar.

您可以使用parboiled并声明一个小语法。

回答by ant

Another alternative :

另一种选择:

public static void main(String[] args) throws IOException
    {

        String patternString = " 1 ON OFF";
        boolean pass = true;

            if (patternString.charAt(0) != ' ' && patternString.charAt(2) != ' ') {
                pass = false;
            }

            int digit = Character.getNumericValue(patternString.charAt(1));

            if (digit < 0 && digit > Integer.MAX_VALUE) {
                pass = false;
            }

            if (patternString.charAt(3) != 'O' && patternString.charAt(4) != 'N') {
                pass = false;
            }

            if (patternString.charAt(5) != ' ' && patternString.charAt(6) != 'O' && patternString.charAt(7) != 'F' && patternString.charAt(8) != 'F') {
                pass = false;
            }

            if (pass) {
                System.out.println("Validation pass");
            }
    }

回答by pb2q

Try using String.split(" "), to split around the spaces. You'll get an array, and if the first character is blank, the first Stringin the array will be an empty string:

尝试使用String.split(" "), 来分割空格。您将得到一个数组,如果第一个字符为空,则数组中的第一个字符String将是一个空字符串:

String strs[] = " 1 ON OFF".split(" ");

With this example you'll get this array: ["", "1", "ON", "OFF"].

通过这个例子,你会得到这个数组:["", "1", "ON", "OFF"]

If the first character is a space, you'll get the empty string as the first element. If there are 2leading spaces, then you'll see empty strings as the first two elements. The remaining strings will be the space separated tokens from the original string, but if there are additional spaces between the tokens then you'll see additional empty strings as array elements.

如果第一个字符是空格,您将获得空字符串作为第一个元素。如果有2 个前导空格,那么您将看到空字符串作为前两个元素。剩余的字符串将是与原始字符串以空格分隔的标记,但如果标记之间有额外的空格,那么您将看到额外的空字符串作为数组元素。

Looping over the resulting array, including a parseIntfor the number, you'll be able to match the rules that you've described.

循环遍历结果数组,包括parseInt数字的 a,您将能够匹配您描述的规则。

Note that you canuse Scannerto similarly tokenize the string, by setting the delimiter to the empty string:

请注意,您可以使用Scanner到同样的记号化字符串,通过设置分隔符为空字符串:

Scanner sc = new Scanner(str);
sc.useDelimiter("");
System.out.println(sc.next());