开发者

Not grab group match in Ruby Regex

I am trying to break down the following string:

"@command Text1 @command2 Text2"

in Ruby. I want to开发者_开发技巧 take out "Text1" and "Text2" in an array. To do this I am using the scan method and using this:

text.scan(/@* (.*?)(@|$)/)

However, when run, the script is pulling the @ symbol in the middle as a separate match (presumably because the parenthesis are used in Ruby to indicate what string you want to pull out of the input):

Text1
@ 
Text2

My question is, how can I pull out Text1 and Text2 bearing in mind the expression needs to stop matching at both "@" and the end of a string?


If you want a non-capturing group use ?:

text.scan(/@* (.*?)(?:@|$)/)

As a sidenote, your regular expression looks like it might contain an error. Perhaps you meant this instead?

text.scan(/@\w+ (\w+)(?= @|$)/)

The difference is that your expression matches on " foo", which I guess is not intentional.


text.scan(/@* (.*?)(?:@|$)/)'


In your regex, you don't need the parentheses around '@|$'. The following will accomplish the same thing without the '@' being returned in a separate match group:

text.scan(/@* (.*?)[@\$]/)

Since you're looking only for a single character in that group, the square brackets will match any one character within them.


Here's how I'd do it:

text.scan(/@[^\s]* ([^@]*)/)


How does this regex look? http://rubular.com/regexes/13264

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜