Reputation: 1893
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
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
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
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