[英]How do I use look-ahead in regex to match on no character?
I've got a set of regex's within a function that are working rather well for me, but I've encountered a new pattern where they fail. 我在函数中有一组正则表达式,对我来说效果很好,但是我遇到了一个失败的新模式。 This function fails when there are no more characters in the string.
当字符串中没有其他字符时,此函数将失败。 For example my function matches and replaces text in the following: "
1 m is equivalent to...
" becomes " 1 meter is equivalent to...
" However, it fails on: " There are 100 cm in 1 m
" 例如,我的函数匹配并替换以下文本:“
1 m is equivalent to...
”变为“ 1 meter is equivalent to...
”但是,它失败了:“ There are 100 cm in 1 m
”
I'm using AS3, which I believe has a regex engine nearly equivalent to JavaScript's. 我正在使用AS3,我认为它有一个几乎相当于JavaScript的正则表达式引擎。 The current pattern is:
目前的模式是:
[0-9]+ m(?= )|[0-9]+m(?= )
I loop through a list of patterns and replacement strings, so it was easy to add another pattern to the list. 我遍历模式列表和替换字符串,因此很容易将另一个模式添加到列表中。 I tried:
我试过了:
[0-9]+ m(?=)|[0-9]+m(?=)
And: 和:
[0-9]+ m(?='')|[0-9]+m(?='')
And both failed. 两者都失败了。 I'm missing a fundamental tidbit of knowledge.
我错过了一个基本的知识点。 I believe I need to know how to say, "look-ahead and match when there are no other characters in the line"
我相信我需要知道怎么说,“当行中没有其他角色时,前瞻和匹配”
You could simplify your expression by looking for a word boundary ( \\b
); 您可以通过查找单词边界(
\\b
)来简化表达式; something like this: 这样的事情:
var regex = /(\d+)\s*m\b/;
regex.exec('1 m is equivalent to...'); // => ["1 m", "1"]
regex.exec('There are 100 cm in 1 m'); // => ["1 m", "1"]
'行中没有其他字符'相当于'在行尾',所以只需使用$
元字符
You're looking for a word boundry which is represented by the sequence \\b
. 你正在寻找一个由序列
\\b
表示的单词边界。 You could use the expression /\\d+\\s*m\\b/
您可以使用表达式
/\\d+\\s*m\\b/
\d+ - one or more digits
\s* - any number of spaces
m - a literal 'm'
\b - a word boundry
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.