当前位置: 代码迷 >> java >> 如何在Java中字符串的某些部分中使用正则表达式?
  详细解决方案

如何在Java中字符串的某些部分中使用正则表达式?

热度:27   发布时间:2023-07-31 11:47:45.0

我想在Java字符串的某些部分使用正则表达式,

在下面的字符串中,对于所有字符串,只有emp-id-<dynamic empID>project保持相同。

Case1:  project/emp-id1545/ID-JHKDKHENNDHJSJ

Case 2: project/**dep**/emp-id8545/ID-GHFRDEEDE

我有时场景串配备了deptemp ,或像没有价值Case 1project

如何只过滤上述字符串中的emp-id-<dynamic empID> ,以处理情况1和情况2?

您可以通过多种方式完成此任务

正则表达式

模式

"emp-id\\d+"

两种情况下都能实现您想要的功能。 该模式匹配“ emp-id”加上1个或多个数字( \\\\d+ )。

public static void main(String[] args) throws Exception {
    String case1 = "project/emp-id1545/ID-JHKDKHENNDHJSJ";
    String case2 = "project/**dep**/emp-id8545/ID-GHFRDEEDE";

    Matcher matcher = Pattern.compile("emp-id\\d+").matcher(case1);
    // Changed from while to if cause we're only going to get the first match
    if (matcher.find()) {
        System.out.println(matcher.group());
    }

    matcher = Pattern.compile("emp-id\\d+").matcher(case2);
    // Changed from while to if cause we're only going to get the first match
    if (matcher.find()) {
        System.out.println(matcher.group());
    }
}

结果:

emp-id1545
emp-id8545

Java 8

假设您的数据表明字符“ /”是分隔符。 您还可以使用String.split()Stream.filter() (Java 8)查找您的String。

public static void main(String[] args) throws Exception {
    String case1 = "project/emp-id1545/ID-JHKDKHENNDHJSJ";
    String case2 = "project/**dep**/emp-id8545/ID-GHFRDEEDE";

    System.out.println(Arrays.stream(case1.split("/")).filter(s -> s.startsWith("emp-id")).findFirst().get());
    System.out.println(Arrays.stream(case2.split("/")).filter(s -> s.startsWith("emp-id")).findFirst().get());
}

结果:

emp-id1545
emp-id8545

非正则表达式或Java 8

仍然使用“ /”定界符和“ emp-id”,您可以使用String.indexOf()String.substring()提取您要查找的String。

public static void main(String[] args) throws Exception {
    String case1 = "project/emp-id1545/ID-JHKDKHENNDHJSJ";
    String case2 = "project/**dep**/emp-id8545/ID-GHFRDEEDE";

    int index = case1.indexOf("emp-id");
    System.out.println(case1.substring(index, case1.indexOf("/", index)));

    index = case2.indexOf("emp-id");
    System.out.println(case2.substring(index, case2.indexOf("/", index)));
}

结果:

emp-id1545
emp-id8545
  相关解决方案