[英]regular expression extract string between two strings
I am trying to extract strings using regexp. 我正在尝试使用正则表达式提取字符串。 For example in the following string: 例如下面的字符串:
select DESCENDANTS([Customer].[Yearly Income],,LEAVES) on axis(0),
DESCENDANTS([Sales Territory].[Sales Territory],,LEAVES) on axis(1),
DESCENDANTS([Customer].[Total Children],,LEAVES) on axis(2)
from [Adventure Works]
where [Measures].[Internet Sales Amount]
I want to extract the substring between every pair of "DESCENDANTS(" and ",,". 我想提取每对“ DESCENDANTS(”和“ ,,”之间的子字符串。
So the result in this case would be: [Customer].[Yearly Income], [Sales Territory].[Sales Territory], [Customer].[Total Children]
因此,在这种情况下,结果将是: [Customer].[Yearly Income], [Sales Territory].[Sales Territory], [Customer].[Total Children]
Any help is appreciated. 任何帮助表示赞赏。 Thanks in advance. 提前致谢。
If you have your text in a string called query
you can do: 如果您在名为query
的字符串中输入文本,则可以执行以下操作:
query.scan(/DESCENDANTS\((.+),,/).flatten
=> ["[Customer].[Yearly Income]", "[Sales Territory].[Sales Territory]",
"[Customer].[Total Children]"]
Some notes: 一些注意事项:
\\(
matches the literal open bracket \\(
匹配文字右括号 (.+)
remembers the characters between the open bracket and the two commas as a capture (.+)
记住右方括号和两个逗号之间的字符 ()
then scan
will return an array of arrays of the captured parts for each match. 如果regexp包含captures ()
则scan
将为每次匹配返回捕获部分阵列的数组。 In this case there is only 1 capture per match so flatten
can be used to return a single array of all the matches we are interested in. 在这种情况下,每个匹配项只有1个捕获,因此可以使用flatten
返回我们感兴趣的所有匹配项的单个数组。 /DESCENDANTS\(([^,]+),,/
在ruular上看到它
这是一个使用split
的丑陋变体:在“ DESCENDANTS(”和“ ,,”上分割,并接受其他所有子字符串:
s.split(/DESCENDANTS\(|,,/).each_with_index.inject([]) {|m,(e,i)| m << e if i.odd?; m}
.+? 。+? is more safe, it works correctly if SQL is in one line. 更安全,如果SQL在一行中,它可以正常工作。
query.scan(/DESCENDANTS\((.+?),,/).flatten
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.