如何在 Java 中解析这个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/950409/
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-08-11 21:28:11  来源:igfitidea点击:

How to parse this string in Java?

javastring

提问by omg

prefix/dir1/dir2/dir3/dir4/..

前缀/dir1/dir2/dir3/dir4/..

How to parse the dir1, dir2values out of the above string in Java?

如何dir1, dir2在Java中解析上述字符串中的值?

The prefix here can be:

这里的前缀可以是:

/usr/local/apache2/resumes

/usr/local/apache2/resumes

采纳答案by coobird

If you want to split the Stringat the /character, the String.splitmethod will work:

如果要拆分String/字符,该String.split方法将工作:

For example:

例如:

String s = "prefix/dir1/dir2/dir3/dir4";
String[] tokens = s.split("/");

for (String t : tokens)
  System.out.println(t);

Output

输出

prefix
dir1
dir2
dir3
dir4

Edit

编辑

Case with a /in the prefix, and we know what the prefix is:

/前缀中带有 a 的大小写,我们知道前缀是什么:

String s = "slash/prefix/dir1/dir2/dir3/dir4";

String prefix = "slash/prefix/";
String noPrefixStr = s.substring(s.indexOf(prefix) + prefix.length());

String[] tokens = noPrefixStr.split("/");

for (String t : tokens)
  System.out.println(t);

The substring without the prefix "slash/prefix/"is made by the substringmethod. That Stringis then run through split.

不带前缀的子串"slash/prefix/"substring方法生成。那String就是运行了split

Output:

输出:

dir1
dir2
dir3
dir4

Edit again

再次编辑

If this Stringis actually dealing with file paths, using the Fileclass is probably more preferable than using string manipulations. Classes like Filewhich already take into account all the intricacies of dealing with file paths is going to be more robust.

如果这String实际上是在处理文件路径,那么使用File类可能比使用字符串操作更可取。像File这样已经考虑到处理文件路径的所有复杂性的类将更加健壮。

回答by basszero

String s = "prefix/dir1/dir2/dir3/dir4"

String parts[] = s.split("/");

System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...

回答by n3rd

In this case, why not use new File("prefix/dir1/dir2/dir3/dir4")and go from there?

在这种情况下,为什么不使用new File("prefix/dir1/dir2/dir3/dir4")并从那里开始?

回答by Ken

public class Test {
    public static void main(String args[]) {
    String s = "pre/fix/dir1/dir2/dir3/dir4/..";
    String prefix = "pre/fix";
    String[] tokens = s.substring(prefix.length()).split("/");
    for (int i=0; i<tokens.length; i++) {
        System.out.println(tokens[i]);
    }
    }

}

回答by user101375

...
String str = "bla!/bla/bla/"

String parts[] = str.split("/");

//To get fist "bla!"
String dir1 = parts[0];

回答by Scott Stanchfield

If it's a File, you can get the parts by creating an instanceof File and then ask for its segments.

如果它是一个文件,你可以通过创建一个文件实例来获取部分,然后请求它的片段。

This is good because it'll work regardless of the direction of the slashes; it's platform independent (except for the "drive letters" in windows...)

这很好,因为无论斜线的方向如何,它都可以工作;它是独立于平台的(Windows 中的“驱动器号”除外......)

回答by Edward Dale

String str = "/usr/local/apache/resumes/dir1/dir2";
String prefix = "/usr/local/apache/resumes/";

if( str.startsWith(prefix) ) {
  str = str.substring(0, prefix.length);
  String parts[] = str.split("/");
  // dir1=parts[0];
  // dir2=parts[1];
} else {
  // It doesn't start with your prefix
}

回答by Edward Dale

String.split(String regex) is convenient but if you don't need the regular expression handling then go with the substring(..) example, java.util.StringTokenizer or use Apache commons lang 1. The performance difference when not using regular expressions can be a gain of 1 to 2 orders of magnitude in speed.

String.split(String regex) 很方便,但如果您不需要正则表达式处理,则使用 substring(..) 示例, java.util.StringTokenizer 或使用 Apache commons lang 1。不使用正则表达式时的性能差异可以是速度提高 1 到 2 个数量级。

回答by Raghunandan

 String result;
 String str = "/usr/local/apache2/resumes/dir1/dir2/dir3/dir4";
 String regex ="(dir)+[\d]";
 Matcher matcher = Pattern.compile( regex ).matcher( str);
  while (matcher.find( ))
  {
  result = matcher.group();     
  System.out.println(result);                 
}

output-- dir1 dir2 dir3 dir4

输出--dir1 dir2 dir3 dir4

回答by Amit Upadhyay

Using String.splitmethod will surely work as told in other answers here.

使用String.split方法肯定会像这里其他答案中所说的那样工作。

Also, StringTokenizerclass can be used to to parse the String using /as the delimiter.

此外,StringTokenizer类可用于解析字符串/作为分隔符。

import java.util.StringTokenizer;
public class Test
{
    public static void main(String []args)
    {
        String s = "prefix/dir1/dir2/dir3/dir4/..";
        StringTokenizer tokenizer = new StringTokenizer(s, "/");
        String dir1 = tokenizer.nextToken();
        String dir2 = tokenizer.nextToken();
        System.out.println("Dir 1  : "+dir1);
        System.out.println("Dir 2 : " + dir2);
    }
}

Gives the output as :

给出输出为:

Dir 1  : prefix
Dir 2 : dir1

Here you can find more about StringTokenizer.

在这里你可以找到更多关于StringTokenizer 的信息