DarkLite1
DarkLite1

Reputation: 14705

PowerShell Regex match beginning of string

There's a regex that does exactly what I want, but I would like it to be able to only check the beginning of the string and don't look at the stuff coming after it.

Working regex:

[RegEx]$RegEx = "(.+?) (.+?)-(.+?)-(.+?)$"

Failed attempts:

[RegEx]$RegEx = "^((.+?) (.+?)-(.+?)-(.+?))"
[RegEx]$RegEx = "\A(.+?) (.+?)-(.+?)-(.+?)"

Examples:

# Ok:
BEL Green-Fruit-Appel Stuff
BEL Green-Fruit-Appel Other stuff stuff

# Not ok (without anything):
BEL Green-Fruit-Appel            

More info here

Thank you for your help.

Upvotes: 5

Views: 21312

Answers (1)

Keith Hill
Keith Hill

Reputation: 201662

Ditch the $ and use ^:

C:\PS> 'BEL Green-Fruit-Appel' -match '^(.+?) (.+?)-(.+?)-(.+?)'
True

C:\PS> $matches
Name                           Value
----                           -----
4                              A
3                              Fruit
2                              Green
1                              BEL
0                              BEL Green-Fruit-A

The last capture group is just A because you are using the non-greedy ? so it stops after the first char. If you want the whole word, change the last capture group to `-(\w+)'.

Upvotes: 5

Related Questions