0

I have the following string ...

CN=KendallLDAPTEST Weihe,OU=CORPUSERS,OU=CORP,DC=int,DC=appriss,DC=com

and I need to extract KendallLDAPTEST Weihe

in other words I need to extract all string data between the first = and the first ,

4 Answers 4

9

Tested, works

Using regex:

str = "CN=KendallLDAPTESTWeihe,OU=CORPUSERS,OU=CORP,DC=int,DC=appriss,DC=com"

str[/\=(.*?),/,1]

For anyone re-using this, replace both instances of here with the characters you want to find the text in between:

[/\here(.*?)here/,1]
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply break the string apart using split on , to first produce an array of key=value pairs, and then split those pairs on =.

str = 'CN=KendallLDAPTEST Weihe,OU=CORPUSERS,OU=CORP,DC=int,DC=appriss,DC=com'

pairs = str.split(',').map { |pair| pair.split('=') }
# => [["CN", "KendallLDAPTEST Weihe"], ["OU", "CORPUSERS"], ["OU", "CORP"], ["DC", "int"], ["DC", "appriss"], ["DC", "com"]]

pairs.first[1]
# => "KendallLDAPTEST Weihe"

This is somewhat naive in that it will not work if any of your data contains escaped = or , characters.

Comments

1

I'd use:

str = "CN=KendallLDAPTEST Weihe,OU=CORPUSERS,OU=CORP,DC=int,DC=appriss,DC=com"
str[/=([^,]+)/, 1] # => "KendallLDAPTEST Weihe"

By default the regular expression will find the first match then stop. This simply finds the first =, then captures all characters that are not , until the first ',' and returns it.

Comments

0

If the text you are trying to capture is always appearing on the same index you can use this:

the_text[3...22]

2 Comments

I need to do this for numerous different strings of different lengths
I see, then I believe @nextstep provided the best option. Sorry it was not as useful as I though it would be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.