简体   繁体   中英

simple regular expression pattern match

i'm trying to use a regex but i can't find the right result.

Pattern pattern = Pattern.compile(" - ");
Matcher matcher = pattern.matcher("test - test2");

It should give me "test"

    while (matcher.find()) {
        String fichierPart1 = matcher.group(1);
    }

I can't get the result with this code. Thank you for your help

There is no group 1 - there is only one match, " - ".

An online regex tester makes this much easier to understand.

If you want to get "test", why not do "test - test".split(" - ") ? This returns an array of the values separated by - - test and test in your case.

Your pattern should be something difficult: regexes are not the best bet for splitting texts.

Furthermore, regular expressions have their own syntax, that has to be parsed before getting the pattern evaluated. So, that's a lot of work more your app is trying to do uselessly.

I suggest you, as per the comment by @Wiktor Stribiżew, to use String.split() . Try just this:

for (String part : "test - test2".split(" - ")) {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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