I’m a newbie to ruby, I want to know if I can use just one line to do the job.
Take the ‘search’ of this site for example. When user typed [ruby] regex, I can use following code to get the tag and keyword
'[ruby] regex' =~ /\[(.*?)\](.*)/
tag, keyword = $1, $2
Can we write it just in one line?
UPDATE
Thank you so much! May I make it harder and more interesting, that the input may contains more than one tags, like:
[ruby] [regex] [rails] one line
Is it possible to use one line code to get the tags array and the keyword? I tried, but failed.
You need the
Regexp#matchmethod. If you write/\[(.*?)\](.*)/.match('[ruby] regex'), this will return aMatchDataobject. If we call that objectmatches, then, among other things:matches[0]returns the whole matched string.matches[n]returns the nth capturing group ($n).matches.to_areturns an array consisting ofmatches[0]throughmatches[N].matches.capturesreturns an array consisting of just the capturing group (matches[1]throughmatches[N]).matches.pre_matchreturns everything before the matched string.matches.post_matchreturns everything after the matched string.There are more methods, which correspond to other special variables, etc.; you can check
MatchData‘s docs for more. Thus, in this specific case, all you need to write isEdit 1: Alright, for your harder task, you’re going to instead want the
String#scanmethod, which @Theo used; however, we’re going to use a different regex. The following code should work:The
input.scan(tag_and_text)will return a list of tag–search-text pairs:The
transposecall flips that, so that you have a pair consisting of a tag list and a search-text list:You can then do whatever you want with the results. I might suggest, for instance
This will concatenate the search snippets with single spaces, get rid of leading and trailing whitespace, and replace runs of multiple spaces with a single space.