简体   繁体   English

Ruby正则表达式行尾

[英]Ruby regular expression end of line

I am trying to find the variables in a string, eg 我正在尝试在字符串中查找变量,例如

"%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 a line break. 文本来自CSV,字符串不以换行符结尾。

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. 我认为$\\z应该匹配行尾,但这似乎不起作用。 How can I capture %2 in the above scenario? 在上述情况下如何捕获%2? (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 . 您的三个匹配结果将存储在特殊变量$1$2$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM