Using regexp to find a string matching multiple randomly ordered words

How can I write a regular expression to match multiple words in random order?

For example, suppose the following lines:

Dave Imma Car Pom Dive
Dive Dome Dare
Imma Car Ryan
Pyro Dave Imma Dive
Lunar Happy Dave

I want to find a line for one corresponding to "Dave", "Imma" and "Dive", waiting for the 1st and 4th lines. Is it possible?

+3
source share
5 answers

If you insist on this with a regex, you can use lookahead:

s.matches("(?=.*Dave)(?=.*Imma)(?=.*Dive).*")

Regex is not the most efficient way to do this.

+3
source

in * nix, you can use awk

if his order

awk '/Dave.*Imma.*Dive/' file

if its not ok

awk '/Dave/ && /Imma/ && /Dive/' file
+2
source
if  ((matches "/(Dave|Imma|Dive) (Dave|Imma|Dive) (Dave|Imma|Dive)/")
 && (contains("Dave")) && (contains("Imma")) && (contains("Dive")))
{
    // this will work in 90% of cases.
}

, . .

0
String[] lines = fullData.split("\n");
String[] names = {"Dave", "Imma", "Dive"};
ArrayList matches = new ArrayList();

for(int i=0; i<lines.size(); i++){
    for(String name : names){
        // If any of the names in the list isn't found
        // then this line isn't a match
        if(!lines[i].contains(name)){
            continue;
        }
    }
    // If we made it this far, all of the names were found
    matches.add(i);
}
// matches now contains {1, 4}

, , :

String[] lines = fullData.split("\n");
String[] names = {"Dave", "Imma", "Dive"};

for(String line : lines){
    for(String name : names){
        // If any of the names in the list isn't found
        // then this line isn't a match
        if(!line.contains(name)){
            continue;
        }
    }
    // If we made it this far, all of the names were found

    // Do something
}
0

?

Dave Imma Dave
Dave Imma Dive Imma

, , , ? , :

^(?:\b(?:(?!(?:Dave|Imma|Dive)\b)\w+[ \t]+)*(?:Dave()|Imma()|Dive())[ \t]*){3}$\1\2\3

"".:) , , . .

(, , $.)

EDIT: : ? , ?

DaveCar PomDive Imma
DaveImmaDive

So far, the only other answer that provides both uniqueness and complete words is Coronatus, and it does not match lines with additional words, such as:

Dave Imma Car Pom Dive
Pyro Dave Imma Dive
0
source

Source: https://habr.com/ru/post/1739570/


All Articles