1

i am trying to get an array that contain of aaaaa,bbbbb,ccccc as split output below.

a_string = "aaaaa[x]bbbbb,ccccc";
split_output a_string.split.split(%r{[,|........]+})

what supposed i put as replacement of ........ ?

1
  • 1
    You have to give some more criteria. For example you just added , as a divisor but, what else do you expect could be there?, for the current example this would work "aaaaa[x]bbbbb,ccccc".split(%r{[,|\[x\]]+}). Commented Sep 30, 2011 at 3:05

2 Answers 2

2

No need for a regex when it's just a literal:

irb(main):001:0> a_string = "aaaaa[x]bbbbb"
irb(main):002:0> a_string.split "[x]"
=> ["aaaaa", "bbbbb"]

If you want to split by "open bracket...anything...close bracket" then:

irb(main):003:0> a_string.split /\[.+?\]/
=> ["aaaaa", "bbbbb"]

Edit: I'm still not sure what your criteria is, but let's guess that what you are really doing is looking for runs of 2-or-more of the same character:

irb(main):001:0> a_string = "aaaaa[x]bbbbb,ccccc"
=> "aaaaa[x]bbbbb,ccccc"
irb(main):002:0> a_string.scan(/((.)\2+)/).map(&:first)
=> ["aaaaa", "bbbbb", "ccccc"]

Edit 2: If you want to split by either the of the literal strings "," or "[x]" then:

irb(main):003:0> a_string.split /,|\[x\]/
=> ["aaaaa", "bbbbb", "ccccc"]

The | part of the regular expression allows expressions on either side to match, and the backslashes are needed since otherwise the characters [ and ] have special meaning. (If you tried to split by /,|[x]/ then it would split on either a comma or an x character.)

Sign up to request clarification or add additional context in comments.

3 Comments

hmm sorry i simplify too much my question description.. i still need to use regex because i have some other logic, this is just one of split criteria (i edit the sample in question)
@iwan I've edited my answer, but your question is still not clear enough. What are the strings you're looking for? What are the strings that will be separating the strings you're looking for.
thanks Phrogz for putting so much effort to help me, basically you've answered my question.. but they are in two different codes (first two). What I need can be summarized as "what is the regular expression to split by comma or by [x] in any random sentence".
1

no regex needed, just use "[x]"

Comments

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.