Ruby regular expression end of line
I am trying to find the variables in a string, e.g.
"%0" can not be found. %1 Please try again %2
I need to know how each variable ends (space, period, end of line) cause I will check for the existence of same variable in the translated version of this string. Text comes from a CSV and strings do not end with 开发者_C百科a line break.
I am able to capture them all except the ones at the end of a string with:
reg = /[%@!][^\s]+[\s\.\z$]+/
I thought either $
or \z
should match end of line but that does not seem to work. How can I capture %2 in the above scenario? (again, there is no line break at the end)
$
matches end-of-line, but not when used inside brackets like that. Writing [$]
is how you would look for the normal dollar-sign character '$'.
If the string you are searching is the exact string you listed above, try
reg = /^"(.*)" can not be found[.] (.*) Please try again (.*)$/
error_string =~ reg
Your three matching results will be stored in the special variables $1
, $2
, and $3
.
Okay, I solved it with a different approach. Using a positive lookahead works as the character class is not needed
/[%@!][\w]+(?=\s|\z|\.|\W)/
For the example string, this returns:
%0
%1
%2
精彩评论