正则表达式正确匹配字符串? [英] Regular Expression to Match String Exactly?
问题描述
我会在提到这个问题前提到,虽然我远离正规表达大师,但对我来说并不完全陌生。构建一个正则表达式来搜索特定字符串中的模式通常对我来说不是问题,但我有一个(可能是?)独特的情况。
I'll preface this question by mentioning that while I'm far from a regular expressions guru, they are not completely foreign to me. Building a regular expression to search for a pattern inside a particular string generally isn't a problem for me, but I have a (maybe?) unique situation.
我有一组值,比如:
028938
DEF567987
390987.456
GHI345928.039
028938
DEF567987
390987.456
GHI345928.039
我想匹配一组特定的字符串,例如:
I want to match a certain set of strings, such as:
- 由6位数字组成的字符串
- 正好由6位数组成的字符串,小数点后跟3位数字
在上面的例子中,第一个和第三个值应匹配。
In the above examples, the first and third values should be matched.
I使用正则表达式:
[0-9]{6}
[0-9]{6}.[0-9]{3}
不幸的是,由于以上所有示例包含指定的模式,所有值都匹配。这不是我的意图。
Unfortunately, since all the above examples contain the specified pattern, all values are matched. This is not my intention.
所以我的问题,简而言之,就是如何编写一个完全匹配字符串的正则表达式,没有其他字符。匹配模式的右侧还是左侧?这种匹配是否有一个术语? (谷歌没有帮助。)TIA
So my question, in a nutshell, is how to write a regular expression that matches a string exactly and completely, with no additional characters to the right or left of the matched pattern? Is there a term for this type of matching? (Google was no help.) TIA
推荐答案
使用 ^
和 $
匹配字符串的开头和结尾
use ^
and $
to match the start and end of your string
^[0-9]{6}$
^[0-9]{6}\.[0-9]{3}$
参考: http://www.regular-expressions.info /anchors.html
此外,正如Mikael Svenson所述,您可以使用边界 \b
如果您在更大的文本块中搜索此模式。
Also, as noted by Mikael Svenson, you can use the word boundary \b
if you are searching for this pattern in a larger chunk of text.
参考: http://www.regular-expressions.info/wordboundaries.html
你也可以写两个一次性使用这些正则表达式
You could also write both those regexes in one shot
^\d{6}(\.\d{3})?$
这篇关于正则表达式正确匹配字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!