我需要获取位于两个相同或不同定界符之间的子字符串。定界符将在字符串中出现多次,因此我需要提取位于定界符1的第m次出现和定界符2的第n次出现之间的子字符串。例如:
myString : Ron_CR7_MU^RM^_SAF_34^
如果我需要提取介于“ _”的第三次出现和“ ^”的第三次出现之间的子字符串,该怎么办?
Substring = SAF_34
或者我可以寻找位于第二个'^'和第四个'_'之间的子字符串,即:
Substring = _SAF
SQL等效项为:substr(myString,instr(myString,' ',1,3)+ 1,instr(myString,'^',1,3)-1-instr(myString,' ',1,3) )
我会用
public static int findNth(String text, String toFind, int count) {
int pos = -1;
do {
pos = text.indexOf(toFind, pos+1);
} while(--count > 0 && pos >= 0);
return pos;
}
int from = findNth(text, "_", 3);
int to = findNth(text, "^", 3);
String found = text.substring(from+1, to);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句