I have a string in Ruby like this:
我有一个像这样的Ruby字符串:
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"
.
我想根据“Test Spec:”检索字符串的一部分。在这种情况下,我希望结果是"somespecname"
How can I do it in Ruby?
用Ruby怎么做呢?
4 个解决方案
#1
2
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.
查看OP的示例,我假设在某些情况下,要检索的字符串可能包含非单词字符。这个正则表达式也可以正确地捕获它们。
var.match(/^Test Spec:\s*(.*?)\s*$/)[1]
#2
2
Do this:
这样做:
var.match(/Spec:\s*(\w+)/)[1] # => "somespecname"
#3
1
You can divide the string into array elements using split for easier reference than regex or match.
可以使用split将字符串分割为数组元素,以便比regex或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 "
#4
1
You could use the String#[]
and String#strip
methods:
您可以使用String#[]和String#strip方法:
var[/Test Spec:(.*)$/, 1].strip
# => "somespecname"
Update: An alternative expression using lookbehind:
更新:使用lookbehind的另一个表达式:
var[/(?<=Test Spec:).*$/].strip
#1
2
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.
查看OP的示例,我假设在某些情况下,要检索的字符串可能包含非单词字符。这个正则表达式也可以正确地捕获它们。
var.match(/^Test Spec:\s*(.*?)\s*$/)[1]
#2
2
Do this:
这样做:
var.match(/Spec:\s*(\w+)/)[1] # => "somespecname"
#3
1
You can divide the string into array elements using split for easier reference than regex or match.
可以使用split将字符串分割为数组元素,以便比regex或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 "
#4
1
You could use the String#[]
and String#strip
methods:
您可以使用String#[]和String#strip方法:
var[/Test Spec:(.*)$/, 1].strip
# => "somespecname"
Update: An alternative expression using lookbehind:
更新:使用lookbehind的另一个表达式:
var[/(?<=Test Spec:).*$/].strip