Reputation: 21
I have a string like this:
Adam Nguyen(adamnguyen)
What is the best way to get two strings "Adam Nguyen"
and "adamnguyen"
?
Upvotes: 2
Views: 962
Reputation: 1278
Given:
name = 'Adam Nguyen(adamnguyen)'
If the input is always short like the example and you're not performing this operation too many times (i.e. performance is not an issue), and the format of the string is guaranteed not to vary, I find the following to be slightly more verbose, but more intelligible than regex:
human_readable_name, other_name = name.split('(')
other_name = other_name[0..-2]
But if it needs to scale, regex is the way to go:
human_readable_name, other_name = name.split(/[()]+/);
Upvotes: 1
Reputation: 168209
"Adam Nguyen(adamnguyen)".split(/[()]+/)
# => ["Adam Nguyen", "adamnguyen"]
Upvotes: 6
Reputation: 223133
name, username = /^(.*?)\s*\((.*)\)$/.match('Adam Nguyen (adamnguyen)').captures
Upvotes: 1