w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Reqular expression - Searching a string using regex and extracting the match from the original string

By replacing those non-digit characters, you're making your task difficult. Rather you should make a regex that extracts that part directly from the string.

The issue here is, you can't directly do \d{12}, as the digits are not contiguous. So, let's modify that part. Since you can have 0 or more non-digit characters in between, you can use - \d\D* instead of \d, and apply match that 11 times, and at the end, match single digit.

So you can use the following regex:


Use it with Matcher#find() method, and get the entire group out of it.

String str = "Lorem ipsum XYZ1234-123456-12 lorem ipsum";

Pattern pattern = Pattern.compile("[a-zA-Z]{3}(\d\D*){11}\d");
Matcher matcher = pattern.matcher(str);

if (matcher.find()) {




If the separators between digits are non-alphanumeric, then you can use [\W_] instead of \D, as already pointed out by @Pshemo in comments:


© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.