Java中的正则表达式匹配

发布于 2025-01-02 00:40:15 字数 375 浏览 3 评论 0原文

我正在尝试在Java中生成一个正则表达式匹配,它接受包含3和7的所有数字(以任何顺序,即所有3都应该至少有一个7,反之亦然)整数集。到目前为止,我已经编写了下面的代码,但是我无法获得正确的输出。任何形式的帮助将不胜感激:

class Main {
  public static void main (String[] args) throws java.lang.Exception {
    System.out.println("333333".matches("[[3][7]+]*") ? "Yes" : "No");
  }
}

在这里,我应该得到输出为“否”,因为给定的字符串只是 3,而不是 3,并且至少有一个 7。

I am trying to generate a regular expression match in Java, that accepts all numbers that contain 3 and 7 (in any order, ie there should be at least one 7 for all 3's and vice versa) over the set of integers. So far, I have written the code below, however I am not able to get the correct output. Any kind of help will be appreciated:

class Main {
  public static void main (String[] args) throws java.lang.Exception {
    System.out.println("333333".matches("[[3][7]+]*") ? "Yes" : "No");
  }
}

Here, I should be getting the output as NO, since the given string is only of 3's not of 3 and at least one 7.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凯凯我们等你回来 2025-01-09 00:40:16

我不确定是否需要正则表达式。为什么不使用以下内容:

public static boolean containsDigit(int n, int digit) {
    return String.valueOf(n).contains(String.valueOf(digit));
}

...

int n = 333333;
boolean nContains3And7 = containsDigit(n, 3) && containsDigit(n, 7);

I'm not sure if a regex is necessary. Why not use the following:

public static boolean containsDigit(int n, int digit) {
    return String.valueOf(n).contains(String.valueOf(digit));
}

...

int n = 333333;
boolean nContains3And7 = containsDigit(n, 3) && containsDigit(n, 7);
落叶缤纷 2025-01-09 00:40:16

根据您的描述,这应该足够了:

String input = "333333";
// Input string contains both a 3 and a 7.
System.out.println(((input.indexOf("3") > -1) && (input.indexOf("7") > -1)) ? "Yes" : "No");

由于正则表达式检查字符序列,因此此练习变得不必要的复杂。

From your description, this should be sufficient:

String input = "333333";
// Input string contains both a 3 and a 7.
System.out.println(((input.indexOf("3") > -1) && (input.indexOf("7") > -1)) ? "Yes" : "No");

Since a regex examines a sequence of characters, this exercise becomes unnecessarily complicated.

月隐月明月朦胧 2025-01-09 00:40:16

^(\d*3\d*7\d*)|(\d*7\d*3\d*)$ 我想。

^(\d*3\d*7\d*)|(\d*7\d*3\d*)$ I think.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文