Search code examples
arraysrubystringcharactervariable-length

How do I select 3 character in a string after a specific symbol


Ok, so let me explain. I have some string like this : "BAHDGF - ZZZGH1237484" or like this "HDG54 - ZZZ1HDGET4" I want here to select the triple Z (that are obviously 3 differents character but for the example I think it's more comprehensible for you).

So, my problem is the next : The first part has a modulable length but i can just ignore it, I need something to take the triple Z so I was thinking about something that can "slice" my string after the " - ".

I started to try using "partition" but I just failed lamentably. I just get kinda lost with the news 3 array and then take the first 3 letter of one of the array, well, it seems very complicated and i think I'm just passing by an obvious solution that I can't find actually. It's been something like 2 days that i'm on it without anything in my mind that can help me, sort of blank page syndrome actually and I really need a little help to unlock this point.


Solution

  • Given:

    examples=[ "BAHDGF - ZZZGH1237484", "HDG54 - ZZZ1HDGET4" ]
    

    You could use a regex:

    examples.each {|e| p e, e[/(?<=-\s)ZZZ/]}
    

    Prints:

    "BAHDGF - ZZZGH1237484"
    "ZZZ"
    "HDG54 - ZZZ1HDGET4"
    "ZZZ"
    

    Or .split with a regex:

    examples.each {|e| p e.split(/-\s*(ZZZ)/)[1] }
    'ZZZ'
    'ZZZ'
    

    If the 3 characters are something other than 'ZZZ' just modify your regex:

    > "BAHDGF - ABCGH1237484".split(/\s*-\s*([A-Z]{3})/)[1]
    => "ABC"
    

    If you wanted to use .partition it is two steps. Easiest with a regex partition and then just take the first three characters:

    > "BAHDGF - ABCGH1237484".partition(/\s*-\s*/)[2][0..2]
    => "ABC"