ruby - Substring starting with a combination of digits till the next white space -
I have a very long string of 2,000 characters string regions with the first two characters of each segment as a segment indicator Is to join.
Eg- '11xxxxx 12yyyy 14ddddd gghgfbddc 087668658 9 Sandra Collins 201 STMONK Ca'
Now I want sector indicator to extract 14.
I have achieved it:
str.split ('') .each do | Substr | If substr.starts_with? ( '14') key = substr.slice (2,5) break .to_i end end
I feel there must be a better way to do it. I can not find more direct and one line solution for string matching in Ruby. Please suggest a better approach.
not entirely clear who are looking for because shows your example string characters, but Your title points out. Either way, it's a good job for a regular expression pattern: Of these Which is suitable for your use-case, in fact you have to decide on.
foo = '12yyyy 014dddd 14ddddd gghgfbddc' time = '12yyyy 014dddd 1,499,999 gghgfbddc' baz = '12yyyy 014dddd 14a9B9z gghgfbddc' foo [/ \ B14 [a-zA-Z] + /] # = & gt; "14ddddd" bar [/ b14 \ d + /] # = & gt; "1499999" Falcon [/ \ b14 \ w + /] # = & gt; "14 A 9 B 9z" EFU [/ \ B14 \ S + /] # = & gt; "14ddddd" bar [/ b14 \ S + /] # = & gt; "1499999" Falcon [/ \ b14 \ S + /] # = & gt; "14 A 9 B 9z"
\ b is
means the word break, so patterns One must start with the transition between the spaces or punctuation marks. [a-zA-Z] +
means one or more letters. \ d +
. \ w +
means one or more letters, digits and '_'
. This is the reason that the character is equal to setting up [one-zA-Z0-9 _]
. \ s +
means non-white, which is useful if you want everything for a space
Comments
Post a Comment