简体   繁体   English

仅用于数字的 Java 正则表达式

[英]Java REGEX for only numbers

Im working on a personal custom text editor for mysql and this is my issue:我正在为 mysql 开发个人自定义文本编辑器,这是我的问题:

在此处输入图片说明

This is what im currently using, it will highlight any number, i want to exclude numbers directly concatenated to any letter [A-Za-z], any other symbol is not important since some of them are aritmetic symbols.这是我目前使用的,它将突出显示任何数字,我想排除直接连接到任何字母 [A-Za-z] 的数字,任何其他符号都不重要,因为其中一些是算术符号。

private static final String NUMBER_PATTERN = "[0-9]+";

Use this regex to select only numbers that aren't connected to any text使用此正则表达式仅选择未连接到任何文本的数字

\b\d+\b
  • \\d+ allows any number of digits \\d+允许任意数量的数字
  • \\b at the start and the end defines a word boundary so that it doesn't match words like text12 , 9gag , 4chan etc \\b在开头和结尾定义了一个单词边界,以便它不匹配text129gag4chan等单词

Demo: https://regex101.com/r/Fzm2PS/2演示: https : //regex101.com/r/Fzm2PS/2

// Will match 12, 34, 
// Will not match text12, string, 9gag

What you want is a "positive look-behind" construct in your REGEX.您想要的是 REGEX 中的“正向后视”结构。

"[0-9]+(?<=[a-zA-Z])"

Matches:火柴:

the 9 in "a9"; 
the 10 in "B10"; 
the 9 in "a9A"

Doesn't Match:不匹配:

the 9 in "9A"; 
the 10 in "+10"
the 10 in " 10"

Java Regular Expression for only numbers is仅用于数字的 Java 正则表达式是

String regex=". [az]. " // (after the each dot there is *) and then use variable.matches(regex), it will return true if it contains az and false if it contains only numbers String regex=". [az]. " // (每个点后面都有*) 然后使用variable.matches(regex),如果包含az就返回true,如果只包含数字则返回false

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

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