2

I am trying to read a line and parse a value using regular expression in java. The line that contains the value looks something like this,

...... TESTYY912345 .......
...... TESTXX967890 ........

Basically, it contains 4 letters, then any two ASCII values followed by numeric 9 then (any) digits. And, i want to get the value, 912345 and 967890.

This is what I have so far in regular expression,

... TEST[\x00-\xff]{2}[9]{1} ...

But, this skips the 9 and parse 12345 and 67890. (I want to include 9 as well).

Thanks for your help.

0

2 Answers 2

2

You are pretty close. Capture the entire group (9\\d*) after matching TEST\\p{ASCII}{2}. This way, you'll capture the 9 and the following digits:

String s  = "...... TESTYY912345 ......";
Pattern p = Pattern.compile("TEST\\p{ASCII}{2}(9\\d+)");
Matcher m = p.matcher(s);
if (m.find()) {
  System.out.println(m.group(1)); // 912345
}
Sign up to request clarification or add additional context in comments.

Comments

2

See my comment for a working expression, "TEST.{2}(9\\d*)".

final Pattern pattern = Pattern.compile("TEST.{2}(9\\d*)");
for (final String str : Arrays.asList("...... TESTYY912345 .......",
         "...... TESTXX967890 ........")) {
  final Matcher matcher = pattern.matcher(str);
  if (matcher.find()) {
    final int value = Integer.valueOf(matcher.group(1));
    System.out.println(value);
  }
}

See the result on ideone:

912345

967890

This will match any two characters (except a line terminator) for what is XX and YY in your example, and will take any digits after the 9.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.