java 如何用两个正则表达式“_”和“.”切割字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2911005/
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
how to cut string with two regular expression "_" and "."
提问by Mercer
i have a string like this test_1.docand i want to split this string to have 1.doc
我有一个这样的字符串test_1.doc,我想把这个字符串拆分成1.doc
回答by Matthew Flaschen
str.split("_")[1]
回答by polygenelubricants
Always consult the API for this kind of things. Stringwould be a good place to start, and splitis a good keyword to look for, and indeed, you'll find this:
对于此类事情,请始终咨询 API。String将是一个很好的起点,split也是一个很好的关键字来寻找,事实上,你会发现这个:
public String[] split(String regex): Splits this string around matches of the given regular expression.
public String[] split(String regex):围绕给定正则表达式的匹配项拆分此字符串。
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:
请记住,.可能需要转义正则表达式元字符(例如 dot ):
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[]:
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 lastIndexOfinstead:
另一种可能性是您想在最后一个_. 您仍然可以使用正则表达式执行此操作,但使用起来要简单得多lastIndexOf:
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]"
回答by Bozhidar Batsov
str.split("[_.]")will split on both criteria. I'm not sure why the title of your question and its body differ though...
str.split("[_.]")将在两个标准上分开。我不确定为什么你的问题的标题和它的正文不同......
回答by Jesper
What exactly do you mean? You can just do this:
你到底什么意思?你可以这样做:
String s = "test_1.doc";
String[] result = s.split("_");
resultwill then contain two elements containing "test" and "1.doc".
result然后将包含两个包含“test”和“1.doc”的元素。

