How do I extract text that lies between parentheses (round brackets)?

后端 未结 17 1784
鱼传尺愫
鱼传尺愫 2020-11-22 15:12

I have a string User name (sales) and I want to extract the text between the brackets, how would I do this?

I suspect sub-string but I can\'t work out

17条回答
  •  花落未央
    2020-11-22 15:20

    A very simple way to do it is by using regular expressions:

    Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value
    

    As a response to the (very funny) comment, here's the same Regex with some explanation:

    \(             # Escaped parenthesis, means "starts with a '(' character"
        (          # Parentheses in a regex mean "put (capture) the stuff 
                   #     in between into the Groups array" 
           [^)]    # Any character that is not a ')' character
           *       # Zero or more occurrences of the aforementioned "non ')' char"
        )          # Close the capturing group
    \)             # "Ends with a ')' character"
    

提交回复
热议问题