正则表达式如何找到只有两个空格和一个数字?
嗨,我想对这种字符串使用正则表达式,但我不知道如何做到这一点。我尝试使用
\s\s5 来找到这个字符串。但我也找到了一些像 \s\s\s\s5 这样的字符串,
123
4567
5
5
5
5
你可以看到我们需要处理一些结构。 无论如何,我可以匹配
<whitespace><whitespace>5
但不匹配具有两个以上空格的字符串吗?
<whitespace><whitespace><whitespace><whitespace>5
hi i want to use regular expression with this kind of string, but i can't figure out how to do this. i try to use
\s\s5 to find this string. but i also find some string like \s\s\s\s5
123
4567
5
5
5
5
you can see that there are some structure that we i need to deal with.
is there anyway that i can match the
<whitespace><whitespace>5
but not to match the string with more than two whitespace?
<whitespace><whitespace><whitespace><whitespace>5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将正则表达式锚定到行的开头 (
^
):Anchor your regular expression to the start of the line (
^
):您需要表明您正在查找整行:
其中
^
标记行的开头,$
标记行的结尾。它还取决于您使用的语言,因为 Java 的 java.util.regex.Matches 有一个 find() 方法,可以在字符串中进行匹配,还有一个 < code>matches() 方法将匹配整个字符串。
You need to indicate that you're looking for a full line:
where the
^
marks the start of the line and the$
the end of the line.It also depends which language you're working in, because Java's
java.util.regex.Matches
has afind()
method that will match inside a String, and amatches()
method that will match an entire string.在正则表达式语言中,其中 \s 是一个空格:(
这将找到任何跟随 2 个空格的 5 实例,即“abc 5”将匹配;不确定这是您的问题还是您在询问字符串的开头,其他人已经对此做出了回应)
In a regular expression language where \s is a whitespace:
(this will find any instance of 5 which follows 2 whitespaces, i.e. "abc 5" would match; not sure if this is your question or you are asking about beginning of the string, others have responded to that)