-2

In Atom, if I use Ctrl-F with regular expressions, it will highlight all the matches of the regular expression, for example

File:

aaa
b
ccc
d
e
f
gg

Query:

[a-z]{2,}

Highlighted text:

aaa

ccc



gg

But I haven't found a cmdlet to do this in PowerShell

Expected input/output:

$var = @"
aaa
b
ccc
d
e
f
gg
"@

$var -find "[a-z]{2,}"

#Output
aaa
ccc
gg

Is there a way I can do this?

Nico Nekoru
  • 2,840
  • 2
  • 17
  • 38
Nikola Johnson
  • 479
  • 1
  • 4
  • 11

2 Answers2

3

What you are looking for is

$regex = [regex]'[a-z]{2,}'
$regex.Matches($var).value

Explanation:

As in the comments I suggested you look at Powershell using Regex finding a string within a string where the answer demonstrated the [regex]'s datatype .match method. Unfortunately, this only grabs the first result of a regex and is not meant for multiple results, however, matches will get multiple as it is the plural form of match:

.match:

# Define a regex query
$regex = [regex]'[a-z]{2,}'

# Define your variable
$var = @"
aaa
b
ccc
d
e
f
gg
"@

# Query $var
$regex.match($var)
#output


Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 3
Value    : aaa


As you can see this only gets aaa and provides other data like what group it was in, if it succeeded, and other information.

However, if we do the same thing but with the matches method, it will get all 3 results:

$regex.matches($var)
#output


Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 3
Value    : aaa

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 6
Length   : 3
Value    : ccc

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 16
Length   : 2
Value    : gg



Which shows information for all three results. But if we want to narrow down the results to just the values, we can grab the value tag of the variable like

$regex.Matches($var).value
#output
aaa
ccc
gg

Which is (I assume from your question) what you want.

Nico Nekoru
  • 2,840
  • 2
  • 17
  • 38
2

You can use Select-String to get your desired output:

$var = @"
aaa
b
ccc
d
e
f
gg
"@
$var -split '\r\n' | Select-String -Pattern "[a-z]{2,}"

Output:

aaa
ccc
gg
stackprotector
  • 10,498
  • 4
  • 35
  • 64