Question

I am trying to write a Regex with the following rule.

Text on which Regex match needs to be done:

Key: "employeeNo" with value "ABC12345" is already used.

Rule:

 1. Only the number after ABC is changing.

 2. Key: "employeeNo" with value "ABC[Any Number with any length]" is
    already used.

True cases

Key: "employeeNo" with value "ABC12345" is already used.
Key: "employeeNo" with value "ABC987858547" is already used.
Key: "employeeNo" with value "ABC7" is already used.

Falsecases

key is not used
Key: "employeeNo" with value "ABCXYZYZ" is already used.
Key: employeeNo with value ABC7 is already used.

Regex tried

Key: "employeeNo" with value "ABC[0-9]+" is already used.

I also want to check quotes "".

Was it helpful?

Solution

Looks simple enough, you need to escape your double quotes.

String input = "Key: \"employeeNo\" with value \"ABC12345\" is already used.";
Pattern p = Pattern.compile("Key: \"employeeNo\" with value \"(ABC\\d+)\" is already used.");
Matcher m = p.matcher(input);
if (m.find()) {
    System.out.println(m.group());
    System.out.println(m.group(1));
}

Output

Key: "employeeNo" with value "ABC12345" is already used.
ABC12345

If you need the double quotes inside the back-referenced group (group 1), just enclose the escaped double-quotes in the group parenthesis: (\"ABC\\d+\").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top