我想要使用正则表达式精确匹配2次。

huangapple 未分类评论43阅读模式
英文:

I want to match exactly 2 times with regex

问题

我有类似这样的字符串。

>XXXX^^^141409i1^^^XXXX。

我想要匹配其中的这三个 ^ 并且该组恰好出现两次。我写了以下正则表达式,但似乎不起作用。

(?:(\^){3}){2}

编辑

我必须将其拆分并提取中间的数字。关键是该组应该恰好由三个 ^ 组成,而且正好出现两次。如果第一组只有 1 或 2 个 ^,它将停止匹配。该字符串是用户输入,如果他输入的字符串超过了该字符串,例如 XXXX^^^141409i1^^^XXXX^^^^XXXX,则不应匹配最后一组,只匹配前两组。(如果我表达得太含糊,请原谅我。)

编辑2

这个练习的重点是拆分字符串并获取中间的数字,我写了以下代码,但问题在于它会匹配每一个 ^^^,而我只想匹配恰好两次。

String[] split = s.split("(\\^){3}");
英文:

I have something like this string.

>XXXX^^^141409i1^^^XXXX.

I want to match those 3 ^ in a group and the group exactly 2 times. I wrote this but it doesn't seem to work.

(?:(\^){3}){2}

EDIT

I have to split it and extract the number in the middle. The point is that that group should consist of exactly 3 ^ and exactly 2 times. If the first group has only 1 or 2 ^ it will stop matching. That string is user input and if he inputs more than that string, for example XXXX^^^141409i1^^^XXXX^^^^XXXX then it shouldn't match the last group, only the first 2. (Sorry if I'm too ambiguous.)

EDIT2

The point of the exercise is to split the string and get the number in the middle, I wrote this line but the problem is that it matches every ^^^ and i only want to match 2 times exactly.

String[] split = s.split("(\\^){3}"); 

答案1

得分: 0

如果我正确理解您的需求,我希望这能对您有所帮助:

String input = "XXXX^^^141409i1^^^XXXX^^^^XXXX";
Pattern pattern = Pattern.compile(".*?\\^{3}(\\w+)\\^{3}");
Matcher matcher = pattern.matcher(input);

if (matcher.find()) {
    System.out.println("The number in the middle: " + matcher.group(1));
}

输出:

The number in the middle: 141409i1

您可以在这里查看它的工作原理:https://regexr.com/51r9e

英文:

If I correctly understood what you want, I hope this will help you:

String input = "XXXX^^^141409i1^^^XXXX^^^^XXXX";
Pattern pattern = Pattern.compile(".*?\\^{3}(\\w+)\\^{3}");
Matcher matcher = pattern.matcher(input);

if (matcher.find()) {
    System.out.println("The number in the middle: " + matcher.group(1));
}

Output:

The number in the middle: 141409i1

Here you can see how it works: https://regexr.com/51r9e

huangapple
  • 本文由 发表于 2020年4月4日 17:17:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/61026018.html
匿名

发表评论

匿名网友

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

确定