user1788294
user1788294

Reputation: 1893

Extract part of a line from a string

I have a string in Ruby like this:

var = <<EOS

***************************
Test Spec:  somespecname 
Test Case:  get new status
EOS

I want to retrieve the name following the "Test Spec:" part of the string. So in this case I want the result to be "somespecname".

How can I do it in Ruby?

Upvotes: 2

Views: 103

Answers (4)

toro2k
toro2k

Reputation: 19228

You could use the String#[] and String#strip methods:

var[/Test Spec:(.*)$/, 1].strip
# => "somespecname"

Update: An alternative expression using lookbehind:

var[/(?<=Test Spec:).*$/].strip

Upvotes: 1

Stacked-for-life
Stacked-for-life

Reputation: 196

You can divide the string into array elements using split for easier reference than regex or match.

  var = "\n\n\nTest Spec:  somespecname \nTest Case:  get new status"

  var.strip! 
  # => "Test Spec:  somespecname \nTest Case:  get new status" 
  new_var = var.split("\n")
  # => ["Test Spec:  somespecname ", "Test Case:  get new status"]
  test_spec_element = new_var[0]
  # => "Test Spec:  somespecname "
  desired_string = test_spec_element.split(":")[0]
  # => " somespecname "

Upvotes: 1

Agis
Agis

Reputation: 33626

Do this:

var.match(/Spec:\s*(\w+)/)[1] # => "somespecname"

Upvotes: 2

sawa
sawa

Reputation: 168101

Looking at the OP's example, I assume that there are cases when the string to be retrieved may include non-word characters. This regex will capture them correctly as well.

var.match(/^Test Spec:\s*(.*?)\s*$/)[1]

Upvotes: 2

Related Questions