views:

153

answers:

4

hello , i have a string like this test_1.doc and i want to split this string to have 1.doc

+2  A: 
str.split("_")[1]
Matthew Flaschen
A: 

What exactly do you mean? You can just do this:

String s = "test_1.doc";
String[] result = s.split("_");

result will then contain two elements containing "test" and "1.doc".

Jesper
+1  A: 

str.split("[_.]") will split on both criteria. I'm not sure why the title of your question and its body differ though...

Bozhidar Batsov
`[_|.]` matches `_`, `|`, or `.`; to match and underscore or a dot you would use `[_.]`. However, the OP is only trying to split on the underscore.
Alan Moore
My bad, I never got used to Java's sick notion of regular expressions. And was wondering why I didn't need to escape the . :-) As for the question - I got fooled by the title...
Bozhidar Batsov
+1  A: 

Always consult the API for this kind of things. String would be a good place to start, and split is a good keyword to look for, and indeed, you'll find this:

public String[] split(String regex): Splits this string around matches of the given regular expression.

    System.out.println(java.util.Arrays.toString(
        "a b c".split(" ")
    )); // prints "[a, b, c]"

    System.out.println(java.util.Arrays.toString(
        "a_b_c".split("_")
    )); // prints "[a, b, c]"

Do keep in mind that regex metacharacters (such as dot .) may need to be escaped:

    System.out.println(java.util.Arrays.toString(
        "a.b.c".split(".")
    )); // prints "[]"
    System.out.println(java.util.Arrays.toString(
        "a.b.c".split("\\.")
    )); // prints "[a, b, c]"

Here's an example of accessing individual parts of the returned String[]:

    String[] parts = "abc_def.ghi".split("_");
    System.out.println(parts[1]); // prints "def.ghi"

As for what you want, it's not clear, but it may be something like this:

    System.out.println(java.util.Arrays.toString(
        "abc_def.ghi".split("[._]")
    )); // prints "[abc, def, ghi]"

It's also possible that you're interested in the limited split:

    System.out.println(java.util.Arrays.toString(
        "abc_def_ghi.txt".split("_", 2)
    )); // prints "[abc, def_ghi.txt]"

Yet another possibility is that you want to split on the last _. You can still do this with regex, but it's much simpler to use lastIndexOf instead:

    String filename = "company_secret_128517.doc";
    final int k = filename.lastIndexOf('_');
    String head = filename.substring(0, k);
    String tail = filename.substring(k+1);
    System.out.printf("[%s] [%s]", head, tail);
    // prints "[company_secret] [128517.doc]"
polygenelubricants