none
Regex: how to read the name of the group of the match directly. RRS feed

  • Question

  • In using the .Net Regular Expression, suppose that I have many non-nested named groups in my pattern (about 20), for a particular match, my question is, how can I know directly the group name of the match without iterating the groups collection ? 

    Suppose that we have the following case: 

    pattern = " (\b\d+\b)|(\b\w+\b))|(\b\w\d+\b)" ; 

    if I get a match m which value is "efg", then m has 4 groups. The first contains "efg", the second is empty, the third contains "efg" and the last is empty also. Now, to know to which group the match "efg" belongs, we must check the first, second and third group. I am trying to avoid this because it is expensive. Can I find the indexes of the non-empty groups in m without checking all the groups in m ? 



    Monday, April 23, 2018 5:58 PM

All replies

  • Just refer to the named grouping construct by its name as demonstrated in the examples to the  MS documentation Grouping Constructs in Regular Expressions.

    For example: 'match.Groups["duplicateWord"].Value'

    wizend

    Monday, April 23, 2018 6:52 PM
  • In doing so, I have to check all the named groups to know which of them the match belongs to. Suppose that we have the following case: 

    pattern = " (\b\d+\b)|(\b\w+\b))|(\b\w\d+\b)" ; 

    if I get a match m which value is "efg", then m has 4 groups. The first contains "efg", the second is empty, the third contains "efg" and the last is empty also. Now, to know to which group the match "efg" belongs, we must check the first, second and third group. I am trying to avoid this because it is expensive. Can I find the indexes of the non-empty groups in m without checking all the groups in m ? 


    Monday, April 23, 2018 9:33 PM
  • Hi hans.sweden,

    Thank you fro posting here.

    For your question, if you want to match efg in 4 groups, we need check all the groups whether it includes efg or not. It takes some time.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, April 24, 2018 7:43 AM
    Moderator