正则表达式测试字符串是否以数字结尾 [英] Regex to test if a string ends with a number

查看:3663
本文介绍了正则表达式测试字符串是否以数字结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试字符串是否以数字结尾。我希望以下Java行打印为true。为什么打印错误?

I'd like to test if a string ends with a a digit. I expect the following Java line to print true. Why does it print false?

System.out.println("I end with a number 4".matches("\\d$"));


推荐答案

你的正则表达式与整个字符串不匹配但只有最后部分。尝试以下代码,它应该工作正常,因为它匹配整个字符串。

Your regex will not match the entire string but only the last part. Try the below code and it should work fine as it matches the entire string.

System.out.println("I end with a number 4".matches("^.+?\\d$"));

您可以对此进行测试,以快速检查此类在线正则表达式测试人员:
< a href =http://www.regexplanet.com/simple/index.html =noreferrer> http://www.regexplanet.com/simple/index.html 。这也为您提供了在结果中使用适当转义的Java代码中应该使用的内容。

You can test this for a quick check on online regex testers like this one: http://www.regexplanet.com/simple/index.html. This also gives you what you should use in the Java code in the results with appropriate escapes.

。+ 将确保至少存在数字前面的一个字符。
将确保它执行懒惰匹配而不是贪婪匹配。

The .+ will ensure that there is atleast one character before the digit. The ? will ensure it does a lazy match instead of a greedy match.

这篇关于正则表达式测试字符串是否以数字结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆