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.
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 \\$
.
If it must absolutely start with a digit, try this:
^\\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
)