0

I have a string like this:

$string = "Test file.cs file.sql file.xml"

I want to check if the string contains a file with .sql and not contains a file with .cs and many other file extensions.

So far I have a very long script to check it:

if($string.Contains(".sql") -and (!$string.Contains(".cs") -or (!$string.Contains(".js")))) # and more....

Is there easy way to do it?

Something like:

$ext = "cs,css,js,xml"
if(!$string.Cotnains($ext))

3 Answers 3

1

I'd suggest regex here:

$exts= '\.(cs|css|js|xml)'
$string = 'Test file.cs file.sql file.xml'

$string -notmatch $extensions
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe I understood the question wrong, but you may want to look at the -in operator like so:

$string = "Test file.cs file.sql file.xml"
$extensions = "cs", "css", "js", "xml"

if ($string -in $extensions) {
    "$string not in ext"
} else {
    "$string in ext"
}

Comments

0

An alternative to the valuable TheIncorrigible1's answer:

$extsContain = '\.(sql)\b'
$extsRefused = '\.(cs|css|js|xml)\b'
$strings =  'Test1 file.cs  file.sql file.xm',
            'Test2 file.ces file.qls file.yml',
            'Test3 file.csa file.sql file.xml',
            'Test4 file.csa file.sql file.pxml',
            'Test5 file.csa file.rql file.axml'

@($strings) -match $extsContain -notmatch $extsRefused

Output:

D:\PShell\SO\57291315.ps1
Test4 file.csa file.sql file.pxml

1 Comment

Note that this will only work if you're testing against an array, otherwise the second match will be testing against the string literal True or False.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.