-4

How to extract last X digits from fixed Y digit number using RegEx?

input : 1234567890123456

  • ((?=\d{16}$)\d{10}|) gives 1234567890

But

  • ((?=\d{16}$)\d{10}$|) does not give 7890123456

basically, I want last 10 digits if it is compulsory 16 digit no else nothing.

4

3 回答 3

0

How to extract last X digits from fixed Y digit number using RegEx?

.{X}$

where X is number of digits you want to extract

于 2017-12-05T10:41:40.050 回答
0

You can see from regex101 that the regex ^\d{6}(\d{10})$ will check if there is 16digit from start to end of the String (so check the length) and capture the last 10.

  • ^ : start of the String
  • \d{6} : first 6 digit
  • (\d{10}) : capture 10 digit
  • $ : end of the String

So you can use it in Java with

String s = "1234567890123456";
Pattern p = Pattern.compile("^\\d{6}(\\d{10})$");
Matcher m = p.matcher(s);
if(m.matches()){
    System.out.println(m.group(1));
}

This can be checked on this ideone

You just have to add an else clause to print that the String is not valid.

于 2017-12-05T11:15:38.213 回答
0

Looks like you're not using Java and cannot use capture groups.

For your tibco tool you can use this regex with validation of 16 digits to grab last 10 digits:

(?<=^\d{6})\d{10}$

RegEx Demo

RegEx Breakup:

  • (?<=^\d{6}) is a positive lookbehind to assert that we have 6 digits from start to previous position
  • \d{10}$ matched 10 digits at the end of string
于 2017-12-05T11:15:40.007 回答