简体   繁体   English

匹配左侧一个条件的Java正则表达式

[英]Java regular expression that match one condition on the left

I need help with a Java regular expression that satisfies the conditions in my parseDouble method. 我需要有关满足我的parseDouble方法中条件的Java正则表达式的帮助。 Regex should only match if two conditions are met: 仅当满足两个条件时,正则表达式才应匹配:

  • representation can be any of integer, backspace, dot, dash 表示形式可以是整数,退格,点,破折号中的任何一个
  • representation must contain integer 表示形式必须包含整数

public class RegexpDemo {
    public static void main(String[] args) {
        test();
    }

    private static boolean parseDouble(final String representation) {
        // only matches if representation is either a backspace, integer, . or -
        // and if no integer is present at all in representation (despite the others present),
        // e.g "krest .ter" then there should not be a match
        final String regex = "[\\s\\d\\.-]";
        try {
            if (representation.matches(regex)) {
                return true;
            } else {
                return false;
            }
        } catch (NumberFormatException nfe) {
            System.out.println("Exception occurred");
            return false;
        }
    }

    private static void test() {
        /*
         * Expected sample test result:
         * " " - > true
         * "" - > false
         * "34 90 . 5" -> true
         * "krest ter" -> false
         * "-345.90.34" - > true
         */
        final String test[] = {" ", "", "34 90 . 5", "krest ter", "-345.90.34"};
        for (int i = 0; i < test.length; i++) {
            System.out.println(test[i] + " -> " + parseDouble(test[i]));
        }
    }
}

Finally I got regex that works perfectly on all cases :) 终于我得到了在所有情况下都可以正常工作的正则表达式:)
I think this is what you need: 我认为这是您需要的:

/([\s\d\.-]*(?=[\d]+?)([\s\d\.-]+))/

This is test on your examples. 这是对您的示例的测试

The (?=[]) construction is called Positive Lookahead . (?=[])构造称为正向超前 You can even do if-else constructions with that! 您甚至可以使用它来进行if-else构造!
Like this: 像这样:

/(?=(?=if_smth)then|else)/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM