简体   繁体   中英

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.

[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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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