Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
986 views
in Technique[技术] by (71.8m points)

regex - Regular Expression That Contains All Of The Specific Letters In Java

I have a regular expression, which selects all the words that contains all (not! any) of the specific letters, just works fine on Notepad++.

Regular Expression Pattern;

^(?=.*B)(?=.*T)(?=.*L).+$

Input Text File;

AL
BAL
BAK
LABAT
TAL
LAT
BALAT
LA
AB
LATAB
TAB

And output of the regular expression in notepad++;

LABAT
BALAT
LATAB

As It is useful for Notepad++, I tried the same regular expression on java but it is simply failed.

Here is my test code;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.lev.kelimelik.resource.*;

public class Test {

    public static void main(String[] args) {
        String patternString = "^(?=.*B)(?=.*T)(?=.*L).+$";

        String dictionary = 
                "AL" + "
"
                +"BAL" + "
"
                +"BAK" + "
"
                +"LABAT" + "
"
                +"TAL" + "
"
                +"LAT" + "
"
                +"BALAT" + "
"
                +"LA" + "
"
                +"AB" + "
"
                +"LATAB" + "
"
                +"TAB" + "
";

        Pattern p = Pattern.compile(patternString, Pattern.DOTALL);
        Matcher m = p.matcher(dictionary);
        while(m.find())
        {
            System.out.println("Match: " + m.group());
        }
    }

}

The output is errorneous as below;

Match: AL
BAL
BAK
LABAT
TAL
LAT
BALAT
LA
AB
LATAB
TAB

My question is simply, what is the java-compatible version of this regular expression?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change your Pattern to:

String patternString = ".*(?=.*B)(?=.*L)(?=.*T).*";

Output

Match: LABAT
Match: BALAT
Match: LATAB

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...