Split string content by parenthesis

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

Answers (3)

Shannon Scott Schupbach
Shannon Scott Schupbach

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

sawa
sawa

Reputation: 168209

"Adam Nguyen(adamnguyen)".split(/[()]+/)
# => ["Adam Nguyen", "adamnguyen"]

Upvotes: 6

C. K. Young
C. K. Young

Reputation: 223133

name, username = /^(.*?)\s*\((.*)\)$/.match('Adam Nguyen (adamnguyen)').captures

Upvotes: 1

Related Questions