需要一个正则表达式,它将在字符串结尾处的字符串中出现4个特定字符后接受字符串。
String test = "012.345.Sub_16462_52034247_20151130_.xlsx";
这里我只需要来自test
字符串的16462_52034247_20151130。
尝试获取16462_52034247_20151130_.xlsx,以便我可以在点之前过滤掉内容。在我的情况下,特定的charatcer是" _"
答案 0 :(得分:1)
String result = test.subSequence(test.indexOf("_")+1, test.lastIndexOf("_")).toString();
System.out.println(result);
输出:16462_52034247_20151130
答案 1 :(得分:1)
我正在写这个答案,假设我正确理解你的要求。如果我错了,请纠正我。
这个答案提供了一个函数,可以根据以下事实从字符串中提取子字符串:
以下是代码段:
public static void main (String[] args)
{
/* Function Call */
System.out.println(getSubstring("012.345.Sub_16462_52034247_20151130_.xlsx",'_'));
}
/**
* Get Sub-String Function
* Arguments: Original String, Search Char
* Output: Filtered Sub-String
**/
public static String getSubstring(String originalString, char searchChar) {
/* Char Occurrence */
int occurrence = 4;
/* Last Position */
int position = originalString.lastIndexOf(searchChar);
/* Search nth Last Occurrence */
while (occurrence -- > 1 && originalString.lastIndexOf(searchChar, position-1) != -1)
position = originalString.lastIndexOf(searchChar, position-1);
/* Add Additional Filter & Return Sub-String */
return originalString.substring(position+1,originalString.lastIndexOf('.') - 1);
}
输出:
16462_52034247_20151130
答案 2 :(得分:0)
在询问SO之前,您必须搜索更多内容。
要从字面上回答这个问题,这里有一个有效的代码:
final String test="012.345.Sub_16462_52034247_20151130_.xlsx";
final String[] s = test.split("_");
String result = "";
for (int i = s.length -4; i < s.length -1; i++) {
result += s[i] + "_";
}
result = result.substring(0, result.length()-1);
System.out.println(result);
输出为:16462_52034247_20151130