繁体   English   中英

如何在第n次出现分隔符之前进行子串?

[英]How to substring before nth occurence of a separator?

first;snd;3rd;4th;5th;6th;...

如何在第三次出现之后拆分上述内容; 分隔器? 特别是不必将value.split(";")整个字符串作为数组,因为我不需要将值分开。 只是字符串的第一部分直到第n次出现。

期望的输出将是: first;snd;3rd 我只需将其作为字符串子字符串,而不是拆分分隔值。

使用Apache的StringUtils.ordinalIndexOf()

查找String中的第n个索引,处理null。 此方法使用String.indexOf(String)。

参数:

str - 要检查的String,可以为null

searchStr - 要查找的String,可以为null

序数 - 要搜索的第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;
}

我会选择这个,简单而基本的:

String 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));

输出:

第一; SND;第三

您可以使用所需的参数数量更改循环中的3

如果你想使用正则表达式,它非常简单:

import re
value = "first;snd;3rd;4th;5th;6th;"
reg = r'^([\w]+;[\w]+;[\w]+)'
re.match(reg, value).group()

输出:

"first;snd;3rd"

这里有更多选择。

您可以使用正则表达式使用否定字符类来匹配字符串的开头而不是分号。

然后重复2次匹配分号的分组结构,然后不分号1次。

^[^;]+(?:;[^;]+){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
}

请参阅Java演示

如果你不想使用split,只需在for循环中使用indexOf就可以知道第3个和第4个“;”的索引。 然后在这些索引之间做一个子串。

你也可以使用与第3个匹配的正则表达式进行拆分; 但它可能不是最好的解决方案。

如果您需要经常这样做,最好在静态Pattern实例中预先编译正则表达式:

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'替换为您想要的元素数量。

下面的代码找到';'的第三次出现的索引 字符和make substring。

String s = "first;snd;3rd;4th;5th;6th;";
String splitted = s.substring(0, s.indexOf(";", s.indexOf(";", s.indexOf(";") + 1) + 1));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM