Regular Expression

Welcome Forums General PowerShell Q&A Regular Expression

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
4 years, 2 months ago.

  • Author
    Posts
  • #19213

    Participant
    Points: 0
    Rank: Member

    I'm trying some regular expression and I found one interesting thing.
    This is TRUE:

    >_ "Zilinec" -match "Z*ec"
    True
    

    which is OK.

    But when I limit "Z" only for beggining of the string:

    >_ "Zilinec" -match "^Z*ec"
    False
    

    it gives me False. Why? 🙂

  • #19214

    Member
    Points: 0
    Rank: Member

    In regex, * is a quantifier that means the previous pattern must be repeated zero or more times. In this case, your pattern states that the string must begin with zero or more Z characters (which it does), followed by the letters "ec" (which it does not.) If you want that * to match any number of characters _after_ the Z (which is how it would work in a wildcard pattern passed to the -like operator), you need to use another special regex character, the period. This matches any single character, and then you can put a * after it to mean (any number of other characters):

    "Zilinec" -match "^Z.*ec$"
    

    (The $ character at the end of the pattern means that must be the end of the string, so it wouldn't match "Zilinec Something Else")

    • #19229

      Participant
      Points: 0
      Rank: Member

      Thank you for a explanation 🙂 I forgot about ".".

The topic ‘Regular Expression’ is closed to new replies.