hello , i have a string like this test_1.doc
and i want to split this string to have 1.doc
views:
153answers:
4What 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".
str.split("[_.]")
will split on both criteria. I'm not sure why the title of your question and its body differ though...
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]"