Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何拆分字符串并提取特定元素?_Java - Fatal编程技术网

Java 如何拆分字符串并提取特定元素?

Java 如何拆分字符串并提取特定元素?,java,Java,我有一个文件,它由以下行组成 20 19:0.26 85:0.36 1064:0.236 # 750 我已经能够逐行阅读并将其输出到控制台。但是,我真正需要的是从每行中提取“19:0.26”“85:0.36”之类的元素,并对它们执行某些操作。如何分割线并获得我想要的元素 使用正则表达式: Pattern.compile("\\d+:\\d+\\.\\d+"); 然后,您可以从此模式创建Matcher对象,并使用其方法find()Java字符串有一个可以调用的拆分方法 String [] st

我有一个文件,它由以下行组成

20 19:0.26 85:0.36 1064:0.236 # 750

我已经能够逐行阅读并将其输出到控制台。但是,我真正需要的是从每行中提取“19:0.26”“85:0.36”之类的元素,并对它们执行某些操作。如何分割线并获得我想要的元素

使用正则表达式:

Pattern.compile("\\d+:\\d+\\.\\d+");

然后,您可以从此模式创建Matcher对象,并使用其方法
find()

Java字符串有一个可以调用的拆分方法

String [] stringArray = "some string".split(" ");
如果愿意,可以使用正则表达式,以便匹配要拆分的特定字符

字符串文档:

模式文档(用于生成正则表达式):
解析一行数据在很大程度上取决于数据是什么样的,以及数据的一致性如何。纯粹从您的示例数据和您提到的“元素”来看,这可能非常简单

String[] parts = line.split(" ");

根据您的要求修改此代码

public class JavaStringSplitExample{

  public static void main(String args[]){

  String str = "one-two-three";
  String[] temp;

  /* delimiter */
  String delimiter = "-";
  /* given string will be split by the argument delimiter provided. */
  temp = str.split(delimiter);
  /* print substrings */
  for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);

  /*
  IMPORTANT : Some special characters need to be escaped while providing them as
  delimiters like "." and "|".
  */

  System.out.println("");
  str = "one.two.three";
  delimiter = "\\.";
  temp = str.split(delimiter);
  for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);

  /*
  Using second argument in the String.split() method, we can control the maximum
  number of substrings generated by splitting a string.
  */

  System.out.println("");
  temp = str.split(delimiter,2);
  for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);

  }

}
公共类JavaStringSplitExample{
公共静态void main(字符串参数[]){
String str=“一二三”;
字符串[]温度;
/*分隔符*/
字符串分隔符=“-”;
/*给定的字符串将由提供的参数分隔符分割*/
temp=str.split(分隔符);
/*打印子字符串*/
对于(int i=0;i
您还需要1064:0.36?本例中的分隔符是空白吗?