我需要获取位于两个相同或不同分隔符之间的子字符串。分隔符将在字符串中出现多次,因此我需要提取位于第 m 次出现的 delimiter1 和第 n 次出现的 delimiter2 之间的子字符串。 例如:
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);
关于java - 两个相同或不同分隔符之间的子字符串(当分隔符多次出现时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22015228/