【问题标题】:Java regex issue to get data in the brackets [duplicate]Java正则表达式问题以获取括号中的数据[重复]
【发布时间】:2018-02-13 13:11:16
【问题描述】:

我想从字符串“Max(percentage(%))”或“Max(percentage)”中获取数据,我需要得到的是括号中的“percentage(%)”或“percentage”。我想使用一个正则表达式来实现目标。有人能帮我吗?以下是我的代码:

String str = "Max(percentage)";
Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))");

String str = "Max(percentage(%))";
Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?<=\\))");

【问题讨论】:

  • 实际尝试将其与某个字符串匹配的Matcher 部分在哪里?
  • (?i)max\((?&lt;val&gt;.+)\)
  • 你的正则表达式有效吗?有什么问题?

标签: java regex


【解决方案1】:

也许你可以试试下面的正则表达式?

 [^\(]*\(([0-9]+)[)%]?\)

【讨论】:

    【解决方案2】:

    下面的正则表达式可以处理一级嵌套括号(为了匹配任意数量的级别,应该使用递归正则表达式,但 java 不支持)。

    正则表达式

    (?<=Max\()[^()]*(?:\([^()]*\)[^()]*)*(?=\))
    

    Java 代码

    String str = "Max(percentage(%))";
    Pattern pattern = Pattern.compile("(?<=Max\\()[^()]*(?:\\([^()]*\\)[^()]*)*(?=\\))");
    

    【讨论】:

      【解决方案3】:

      我会说使用“或”运算符 |检查您是否有百分比或百分比加号 (%):

          String str1 = "Max(32)";
          String str2 = "Max(32(%))";
      
          Pattern pattern = Pattern.compile("Max\\((.+|.+\\(%\\))\\)");
      
          Matcher matcher1 = pattern.matcher(str1);
          if (matcher1.find()) {
              System.out.println("percentage = " + matcher1.group(1));
          }
      
          Matcher matcher2 = pattern.matcher(str2);
          if (matcher2.find()) {
              System.out.println("percentage(%) = " + matcher2.group(1));
          }
      

      【讨论】:

        猜你喜欢
        • 2018-11-20
        • 1970-01-01
        • 1970-01-01
        • 2015-06-23
        • 1970-01-01
        • 1970-01-01
        • 2019-01-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多