3

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
mee
  • 821
  • 5
  • 12
  • 28

3 Answers3

4

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 \\$.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Thanks for the reply. But it gives me an number format exception for the input string "1$04". – mee Mar 06 '13 at 12:12
2

If it must absolutely start with a digit, try this:

^\\d\\$[0-9A-Fa-f]+
  • Thanks for the reply. But it gives me an number format exception for the input string "1$04. Yes, it should start with a digit, followed by "$" and should end with a hex value – mee Mar 06 '13 at 12:19
  • What do you do with the match afterwards? Show the stacktrace of the exception are you getting? –  Mar 06 '13 at 12:21
  • Once it matches, i have to split the string with "$". I couldnt paste the stack trace as it says some indention problem. Will edit my post once Im done indenting – mee Mar 06 '13 at 12:34
  • java.lang.NumberFormatException: For input string: "1$04" – mee Mar 06 '13 at 12:36
  • Refer to this question: http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c –  Mar 06 '13 at 12:39
0

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)

rvalvik
  • 1,559
  • 11
  • 15