简体   繁体   中英

Check that all lines match regex pattern in Java

How to check that all lines match regex pattern in Java.

I mean that I be able to split lines myself in while loop. But is there any library or standard API, which implement this functionality?

UPDATE This is Ruby solution:

if text =~ /PATTERN/

Here's a utility method using Guava that returns true if every line in the supplied text matches the supplied pattern:

public static boolean matchEachLine(String text, Pattern pattern){
    return FluentIterable.from(Splitter.on('\n').split(text))
                         .filter(Predicates.not(Predicates.contains(pattern)))
                         .isEmpty();
}

There is no standard API functionality I know of to do this, however, something like this is easy enough:

string.matches("(What you want to match(\r?\n|$))*+")

Usage:

String string = "This is a string\nThis is a string\nThis is a string";
System.out.println(string.matches("(This is a string(\r?\n|$))*+"));

\\r?\\n covers the most common new-lines.
$ is end of string.
(\\r?\\n|$) is a new-line or the end of string.
*+ is zero or more - but this is a possessive qualifier .

So the whole thing basically checks that every line matches This is a string .

If you want it in a function:

boolean allLinesMatch(String string, String regex)
{
  return string.matches("(" + regex + "(\r?\n|$))*+");
}

Java regex reference .

Prime example of why you need a possessive qualifier:

If you take the string This is a string. repeated a few times (34 times to be exact) but have the last string be This is a string.s (won't match the regex) and have What you want to match be .* .* .*\\\\. , you end up waiting a quite while with * .

* example - runtime on my machine - more than a few hours , after which I stopped it.

*+ example - runtime on my machine - much less than a second .

See Catastrophic Backtracking for more information.

This is one I use

public static boolean multilineMatches(final String regex, final String text) {
    final Matcher m = Pattern.compile("^(.*)$", Pattern.MULTILINE).matcher(text);
    final Pattern p = Pattern.compile(regex);
    while(m.find()) {
        if (!p.matcher(m.group()).find()) {
            return false;
        }
    }
    return true;
}

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