简体   繁体   English

正则表达式检查特殊字符“$”

[英]regular expression to check for special character “$”

I have a string similar to this 9$1F , need to check whether it starts with digit followed by a "$" symbol and should end with a hex value. 我有一个类似于这个9 $ 1F的字符串,需要检查它是否以数字开头后跟一个“$”符号,并且应该以十六进制值结束。

[0-9][\\$][0-9A-Fa-f]

I tried something like this but it fails, can anyone help me please. 我试过这样的东西,但它失败了,任何人都可以帮助我。

You're probably using .matches() (which requires that the regex matches the entire input string), and your regex only matches the first hex digit. 您可能正在使用.matches() (要求正则表达式匹配整个输入字符串),并且您的正则表达式仅匹配第一个十六进制数字。

Try 尝试

[0-9][$][0-9A-Fa-f]+

Instead of [$] , you can also use \\\\$ . 而不是[$] ,你也可以使用\\\\$

如果必须绝对以数字开头,请尝试以下方法:

^\\d\\$[0-9A-Fa-f]+

If you're doing a regex match you might as well just use that to split the string as well. 如果你正在进行正则表达式匹配,你也可以使用它来分割字符串。 The following example converts the digit and hex values into two separate integers. 以下示例将数字和十六进制值转换为两个单独的整数。

final Pattern pattern = Pattern.compile("([0-9])\\$([0-9A-Fa-f]+)");

Matcher matcher = pattern.matcher("9$FF");
int digit = 0;
int hex = 0;

if (matcher.find()) {
    digit = Integer.parseInt(matcher.group(1));
    hex = Integer.parseInt(matcher.group(2), 16);
}
System.out.println(digit + " " + hex);

Results in 9 255 ( 9 and FF ) 结果9 2559FF

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

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