【问题标题】:Java and regular expression, substringJava 和正则表达式、子字符串
【发布时间】:2011-12-29 08:19:07
【问题描述】:

当谈到正则表达式时,我完全迷失了。 我得到生成的字符串,如:

Your number is (123,456,789)

如何过滤掉123,456,789

【问题讨论】:

  • 另外:当您说“过滤掉”时,您的意思是要以“您的号码是 ()”结尾,还是要以数字结尾?
  • 对不起,忘了说生成的字符串可以有不同的大小,否则很容易使用 String.substring 方法使用开始索引和停止索引对其进行子串,但它是不可能,因为字符串的大小不同。但是格式总是你的号码是(xxx,xxx,xxx,xx,xxx,xxx)

标签: java regex substring


【解决方案1】:

您可以使用此正则表达式提取包括逗号在内的数字

\(([\d,]*)\)

第一个捕获的组将拥有您的匹配项。代码将如下所示

String subjectString = "Your number is (123,456,789)";
Pattern regex = Pattern.compile("\\(([\\d,]*)\\)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    String resultString = regexMatcher.group(1);
    System.out.println(resultString);
}

正则表达式的解释

"\\(" +          // Match the character “(” literally
"(" +           // Match the regular expression below and capture its match into backreference number 1
   "[\\d,]" +       // Match a single character present in the list below
                      // A single digit 0..9
                      // The character “,”
      "*" +           // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
")" +
"\\)"            // Match the character “)” literally

这会让你开始http://www.regular-expressions.info/reference.html

【讨论】:

  • 感谢您提供非常好的答案!我也在寻找一个好的参考,所以谢谢你的链接!
【解决方案2】:
String str = "Your number is (123,456,789)";
str = new String(str.substring(16,str.length()-1));

【讨论】:

  • 确切知道字符串使用 '(' 的索引搜索的原因是什么?
  • 当你可以使用其他东西时,不要使用正则表达式。
【解决方案3】:
String str="Your number is (123,456,789)";
str = str.replaceAll(".*\\((.*)\\).*","$1");                    

或者您可以通过以下方式加快替换速度:

str = str.replaceAll(".*\\(([\\d,]*)\\).*","$1");                    

【讨论】:

    【解决方案4】:
    private void showHowToUseRegex()
    {
        final Pattern MY_PATTERN = Pattern.compile("Your number is \\((\\d+),(\\d+),(\\d+)\\)");
        final Matcher m = MY_PATTERN.matcher("Your number is (123,456,789)");
        if (m.matches()) {
            Log.d("xxx", "0:" + m.group(0));
            Log.d("xxx", "1:" + m.group(1));
            Log.d("xxx", "2:" + m.group(2));
            Log.d("xxx", "3:" + m.group(3));
        }
    }
    

    你会看到第一组是整个字符串,接下来的 3 组是你的数字。

    【讨论】:

    • 问题中没有指定。
    【解决方案5】:

    试试

    "\\(([^)]+)\\)"
    

    int start = text.indexOf('(')+1;
    int end = text.indexOf(')', start);
    String num = text.substring(start, end);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多