将给定的输入String与正则表达式列表进行匹配

时间:2018-03-28 15:24:17

标签: java regex

我正在开发一个程序,将给定的架构字符串转换为十进制英寸。例如:12.5'意味着12英尺和6英寸。现在,我还没有进行任何转换。

如何测试给定字符串是否与模式数组列表中的任何模式匹配? 这就是我所拥有的:

Observable.interval

谢谢!

1 个答案:

答案 0 :(得分:0)

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import static org.junit.Assert.*;

@RunWith(JUnit4.class)
public class PatternTest {

    private List<Pattern> patterns;

    @Before
    public void setUp() {
        // List of Patterns
        String wDec = "((\\d+)\\.(\\d+))\\'"; // 12.5'
        String numberWithDoubleQuotes = "^(\\d+)\\\""; // 11"
        String inchesWithForwardDash = "(\\d+)\\/(\\d+)\\\""; // 3/16"

        // Spaces may or may not be used between the feet and inches and the inches and
        // 16ths
        String feetSQSpaceInchesDQ = "(\\d+)\\'(\\s)?(\\d+)\\\""; // 11' 11" OR 11'11"

        // Dashes may or may not be used between feet and inches or between inches and
        // 16ths or both
        String wDash = "(\\d+)\\'(\\-)?(\\d+)\\\""; // 12'-11"
        String wSpacesForwardDash = "(\\d+)\\'\\s+(\\d+)\\s((\\d+)\\/(\\d+))\\\""; // 12' 11 3/16"
        String wSpacesDashForwardDash = "(\\d+)\\'\\s+(\\d+)\\-((\\d+)\\/(\\d+))\\\""; // 12' 11-1/2"

        // Any number of spaces may be used between the feet and inches and the inches
        // and 16ths
        String multipleSpaceForwardDash = "(\\d+)\\'\\s+(\\d+)\\s+((\\d+)\\/(\\d+))\\\""; // 12' 11 1/2"

        // An alternate simpler format using only a contiguous (no spaces) string of
        // digits is also common
        String threeGroupContiguous = "(\\d{2})(\\d{2})(\\d{2})"; // 121103
        String twoGroupContiguous = "^(\\d{2})(\\d{2})"; // 1103
        String oneGroupContiguous = "^(\\d{2})\\b"; // 03

         patterns = new ArrayList<>();
        patterns.add(Pattern.compile(wDec));
        patterns.add(Pattern.compile(numberWithDoubleQuotes));
        patterns.add(Pattern.compile(inchesWithForwardDash));
        patterns.add(Pattern.compile(feetSQSpaceInchesDQ));
        patterns.add(Pattern.compile(wDash));
        patterns.add(Pattern.compile(wSpacesForwardDash));
        patterns.add(Pattern.compile(wSpacesDashForwardDash));
        patterns.add(Pattern.compile(multipleSpaceForwardDash));
        patterns.add(Pattern.compile(threeGroupContiguous));
        patterns.add(Pattern.compile(twoGroupContiguous));
        patterns.add(Pattern.compile(oneGroupContiguous));
    }

    @Test
    public void testInput11(){
        String input = "input1"; //your input here

        assertTrue("Input should match at least once: ", matches(input));

    }

    private boolean matches(String input){
        return patterns.stream().anyMatch( pattern -> pattern.matcher(input).matches());
    }
}