简体   繁体   中英

Ruby remove first word from string

i'm little struggling to find solution of this. How can i remove first word from string like my strings below.

     "i am going to school"

     "he is going to school"

     "she is going to school" 

     "they are going to school"

so string can be any string and don't know about exact length of first word.but just want to remove first word.

The result should be like below

      "am going to school"

     "is going to school"

     "is going to school" 

     "are going to school"

Any help?

Thanks

"i am going to school".split(' ')[1..-1].join(' ')

=> "am going to school"

You can go both ways in an array in ruby so -1 is the last element.

'she is going to school'[/(?<=\\s).*/] => "is going to school"

This uses Ruby's positive lookbehind anchor:

(?<=pat) - Positive lookbehind assertion: ensures that the preceding characters match pat, but doesn't include those characters in the matched text

So the pattern looks for a whitespace character followed by a string of any characters. Since repetition (eg, "*") is greedy, it selects the longest matching string.

Use regexp

str = "i am going to school"
puts str.gsub(/^(\w\s+)(.*)/, '\2')

=> "am going to school"

为每个字符串执行此操作:

string.sub(/\s*[\w']+\s+/, "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM