Regex returning a non-capturing group??

Welcome Forums General PowerShell Q&A Regex returning a non-capturing group??

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

Al
 
Participant
1 year, 10 months ago.

  • Author
    Posts
  • #60651
    ca

    Participant
    Points: 0
    Rank: Member

    Okay, so I am new to regex, or at least to actually writing them, but here is what I have:

    The reference string:

    LDAP://CN=Doe\, John,OU=Users,DC=my,DC=domain

    The regex (that is not working as expected):

    (?:LDAP://CN=)([a-zA-Z]+\\?[,\s]?\s?[a-zA-Z]+)

    Groups matched:

    LDAP://CN=Doe\, Joe
    Doe\, John

    Captured group:

    LDAP://CN=Doe\, John

    What I want to return:

    Doe, John

    By my understanding (which is obviously not correct) I was under the impression that if I included ?: for a captured group it would not return it in the match; and likewise, I do not want to return \ before the , in the middle of the name – which I actually do not know how to exclude a character in a returned result as such. Anyone able to shine some light on the matter?

    Thank you!!

    ca

  • #60666

    Participant
    Points: 10
    Rank: Member

    If you want a non-named capture group, enclose what you want in parentheses. If you want a named capture group, use this syntax. (?'name'regex)

    $string = 'LDAP://CN=Doe\, John,OU=Users,DC=my,DC=domain'
    $string -match 'LDAP://CN=(.*),OU=Users' ; $Matches[1] –replace '\\'
    True
    Doe, John
    
    $string = 'LDAP://CN=Doe\, John,OU=Users,DC=my,DC=domain'
    $string -match "LDAP://CN=(?'name'.*),OU=Users" ; $Matches['name'] –replace '\\'
    True
    Doe, John
    
    • #60669
      ca

      Participant
      Points: 0
      Rank: Member

      @random-commandline

      Nice! Easy to read and to the point. Thank you very much.

      ca

  • #60685
    Al

    Participant
    Points: 0
    Rank: Member

    (?:pattern) is, really, a non capturing group. If you post just the pertinent part of your code, we'll be able to clarify your misunderstanding.

The topic ‘Regex returning a non-capturing group??’ is closed to new replies.