Bluz
Bluz

Reputation: 6490

select-string any string that matches content of other string

Here is my problem :

Say I have a first variable with the value :

$a = "The quick brown fox jumps over the lazy dog."

and another variable with :

$b = "This morning a hunter killed a fox."

The only word that is present in both string is the word fox.

The thing is, I have a collection of 2 arrays, both containing different strings. I would like to know what words are present in both collections given that just like in my example above, a same word can match different strings so I can't simply run

$a | sls $b

because that wouldn't work as I need to use a regexp here but I don't know what regex to use in this context given that every single line in the 2 arrays are unique and any of the words in any line from the array $a could be in array $b.

Before I try to split every string using the space character between the words, and then compare every $split individually with the string from the other array, I was wondering if there's a handy regex expression or some select-string command that can do the job easily ?

Thanks

Upvotes: 1

Views: 433

Answers (3)

CB.
CB.

Reputation: 60918

As per @MDMoore313 you need some replace to remove punctuations i.e. $_.replace('.','')

Give this a try:

 compare-object ( $a | % { $_ -split '\s+' } )  ( $b | % { $_ -split '\s+' } ) -IncludeEqual -ExcludeDifferent

$a and $b are array of strings with words separed by spaces.

Upvotes: 2

MDMoore313
MDMoore313

Reputation: 3311

This is what I came up with. A note, you probably want to implement stronger logic to remove punctuations.

$a = "The quick brown fox jumps over the lazy dog."

$b = "This morning a hunter killed a fox."

$a = $a.Remove($a.IndexOf("."),1)
$b = $b.Remove($b.IndexOf("."),1)

$c = $A.Split(" ")
$d = $B.Split(" ")

$c | foreach{
    $e = $_ 
    $d | foreach{ 
        $f = $_
        if($e -eq $f){
            Write-Host "$e`n"
        }
    }
}

Upvotes: 0

fred02138
fred02138

Reputation: 3361

You could use a regex to create a second regex to do the search. For example:

var $a = "The quick brown fox jumps over the lazy dog.";
var $b = "This morning a hunter killed a fox.";

var r2 = new RegExp($a.replace(/\s/g,"|"), "g");
$b.match(r2);

Yields ["fox"]. (I realize you're probably using PHP -- the above is javascript.)

You would still have to compare every string in the array.

Upvotes: 0

Related Questions