first;snd;3rd;4th;5th;6th;...
我该如何在第三个分号
;
的出现后将上面的内容分割?特别是不必将整个字符串作为数组 value.split(";")
,因为我不需要分开的值。只需要从字符串的开头分离到第n个出现的分号。期望的输出将是:
first;snd;3rd
。
我只需要它作为一个字符串子串,而不是分隔的值。使用Apache的StringUtils.ordinalIndexOf()方法
查找字符串中第n个索引,处理null值。此方法使用String.indexOf(String)。
参数:
str - 要检查的字符串,可以为null
searchStr - 要查找的字符串,可以为null
ordinal - 要查找的第n个searchStr
返回: 搜索字符串的第n个索引,如果没有匹配或输入为空字符串,则为-1(INDEX_NOT_FOUND)
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
ordinalIndexOf()
看起来就是我一直在寻找的。 value.substring(1, StringUtils.ordinalIndexOf(value, ";", 5);
完美地运行! - membersoundString test = "first;snd;3rd;4th;5th;6th;";
int result = 0;
for (int i = 0; i < 3; i++) {
result = test.indexOf(";", result) +1;
}
System.out.println(test.substring(0, result-1));
输出:
第一个;第二个;第三个
当然,您可以在循环中将3
更改为所需参数的数量。
如果您想使用正则表达式,它非常直观:
import re
value = "first;snd;3rd;4th;5th;6th;"
reg = r'^([\w]+;[\w]+;[\w]+)'
re.match(reg, value).group()
输出:
"first;snd;3rd"
More options here .
^[^;]+(?:;[^;]+){2}
解释
^
表示字符串的开头[^;]+
否定字符类匹配非分号1次或多次(?:
开始非捕获组;[^;]+
匹配一个分号和1个以上不是分号的字符){2}
关闭非捕获组并重复2次例如:
String regex = "^[^;]+(?:;[^;]+){2}";
String string = "first;snd;3rd;4th;5th;6th;...";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println(matcher.group(0)); // first;snd;3rd
}
String s = "first;snd;3rd;4th;5th;6th;";
String splitted = s.substring(0, s.indexOf(";", s.indexOf(";", s.indexOf(";") + 1) + 1));
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NthOccurance {
static Pattern pattern=Pattern.compile("^(([^;]*;){3}).*");
public static void main(String[] args) {
String in="first;snd;3rd;4th;5th;6th;";
Matcher m=pattern.matcher(in);
if (m.matches())
System.out.println(m.group(1));
}
}
将“3”替换为您想要的元素数量。