正则表达式匹配每两个破折号,并根据匹配结果修改字符串。

huangapple go评论67阅读模式
英文:

Regex for each two dash and alter string based on the match

问题

我有一个输入,如下所示:

String test = "this-is-name".

我想要检查一个字符串是否遵循这个模式,即 x-y-z,如果遵循这个模式,就简单地返回 z。在我的例子中,应该是 name

我能否得到一个正则表达式,使其匹配确切的两个破折号。

英文:

I have a input as

String test = "this-is-name".

I want to check if a string follows this pattern i.e. x-y-z and if it follows then simply return z. In my example it would be name.

Can I get a regex for the match so that it matches exact two dash.

答案1

得分: 1

这应该可以:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test{

    public static String parseDashes(String test) {
        Pattern exp = Pattern.compile("^([^-]*)-([^-]*)-([^-]*)$");
        Matcher m = exp.matcher(test);
        if (m.matches())
            return m.group(3);
        else
            return null;
    }

   public static void main (String[]args) {
        String test = "this-is-name";
        System.out.println(parseDashes(test));
    }
}

结果:

name

我会突出显示@martinspielmann所做的有用评论...如果您想要求x/y/z的每个部分至少包含一个字符,那么您将使用模式"^([^-]+)-([^-]+)-([^-]+)$"

根据您想要将什么视为有效或无效字符串,有很多选项可供选择。如果您永远不需要捕获'x'和'y',您可以省略前两对括号,然后您将引用group(1)而不是group(3)。可能有一种更紧凑地编写这个模式的花哨方法,利用了相同的模式重复使用的事实。

注意:我更新了原始模式,排除了返回超过两个破折号的情况。

英文:

This should do it:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test{

    public static String parseDashes(String test) {
        Pattern exp = Pattern.compile("^([^-]*)-([^-]*)-([^-]*)$");
        Matcher m = exp.matcher(test);
        if (m.matches())
            return m.group(3);
        else
            return null;
    }

   public static void main (String[]args) {
        String test = "this-is-name";
        System.out.println(parseDashes(test));
    }
}

Result:

name

I'll highlight the helpful comment made by @martinspielmann...if you wanted to require that each of x/y/z consist of at least one character, then you'd use the pattern "^([^-]+)-([^-]+)-([^-]+)$" instead.

There are lots of options here depending on exactly you want to call a valid vs invalid string. You could leave out the first two pairs of parentheses if you were not going to ever need to capture 'x' and 'y', and then you'd refer to group(1) instead of group(3). There's probably a fancy way of writing this more compactly taking advantage of the fact that the same pattern is used repeatedly.

NOTE: I updated my original patterns to exclude cases that return more than two dashes.

huangapple
  • 本文由 发表于 2020年9月23日 05:40:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64018039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定