简体   繁体   中英

Ruby: getting different substrings from string and putting into variables

I have the following string in a textfile:

String:

38561 2914 55532, (aggregated by 55532 202.52.118.114)

Using ruby, how do I read the above string and do the following:

  1. Extract just the substring 55532 from the line and put into a aggregator variable?
  2. Extract 38561 2914 55532 and put into a paths variable?

I'm trying to use a combination of string.scan and string.split with not much luck. All the substrings I would like to extract will change in real life, but they will always be integers. I'm especially struggling to get the aggregator variable populated (task 1) - trying to find a way to get it by starting with [aggregated by ] and ending with [ ] but couldnt get it to work so far. Task 2 ( paths variable) I could achieve with regex, but trying to do both Task 1 and Task2 in a single read/scan, if it makes sense.

Any ideas?

Appreciate it, J

If the string starts with three integers, you can use scan and each_slice like this:

irb> str = '38561 2914 55532, (aggregated by 55532 202.52.118.114)'
irb> paths, aggregator = str.scan(/\d+(?=[ ,])/).each_slice(3).to_a
irb> paths
=> ["38561", "2914", "55532"]
irb> aggregator
=> ["55532"]

or:

arr = str.scan(/\d+(?=[ ,])/)
paths, aggregator = [arr[0..-2], [arr[-1]]]

Another approach with split

line = "38561 2914 55532, (aggregated by 55532 202.52.118.114)"

numbers, aggregatedBy = line.split(", ")

paths = numbers.split(" ") # => 3856,2914,55532
aggregator = aggregatedBy.split(" ")[2] # => 55532

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