简体   繁体   English

Java使用正则表达式拆分将字符串放入数组

[英]Java using regex split to put string into array

I am trying to put a String into an array so I can print the tokens in a different order to how they are in the original file which I am reading from. 我正在尝试将String放入数组中,以便我可以按与读取原始文件时的顺序不同的顺序打印标记。

Below is the code I have so far, I have also included the input file I am reading from. 下面是我到目前为止的代码,我还包括正在读取的输入文件。 What I would like to be able to do is print one word from the original file; 我想做的是从原始文件中打印一个字; system.out.println(tokens[4]); system.out.println(tokens [4]); Which would print 'Species' 哪个会打印“物种”

import java.util.Scanner;

public class inClassTest4Time {

  public static void main(String[] args) {

Scanner scan = new  
Scanner(inClassTest4Time.class.getResourcesAsStream("pet.txt"));
String line;
String[] tokens;
    while (scan.hasNextLine()) 
    {
        line = (scan.nextLine());
        tokens = line.split("//s");
        for (int i = 0; i < tokens.length; i++) {
            System.out.println(tokens[i]);

        }

    }


}
}

Input File: 输入文件:

Pet
===================
- species : String
+ isChipped : boolean
- name : String
- age : int
===================
+ Pet ( String name )
===================

I think you meant to put \\\\s instead of //s . 我认为您打算用\\\\s代替//s //s is actually splitting based on the literal string //s (ie no escaping). //s实际上是根据文字字符串//s拆分//s (即,没有转义)。 Since none of your strings have that, there is no split. 由于您的字符串都没有,所以没有分割。 I suspect that if you do tokens[2] you will get - species : String . 我怀疑如果您执行tokens[2]您将获得- species : String

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

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