Sadu
Sadu

Reputation: 97

Regex Extract number between multiple words combination

Need to extract mobile numbers based on multiple words(LandLine|Mobile) scan from the below input. I am not able to extract all the 3 numbers. Need to read the number before and after the given words combination .Please assist

Words: (LandLine|Mobile)

    String line = "i'm Joe my LandLine number is 987654321, another number 123456789 is my Mobile and wife Mobile number is 776655881";
            
    String pattern = "(Mobile|LandLine)([^\\d]*)(\\d{9})|"  //Forward read
                    +"(\\d{9})([^\\d]*)(Mobile|LandLine)";  //Backward read
    
    Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);

    Matcher matcher = r.matcher(line);
    while(matcher.find()) {
        System.out.println(line.substring(matcher.start(), matcher.end()));
        
    }
Code Output:
LandLine number is 987654321
123456789 is my Mobile and wife Mobile
Expected Output:
LandLine number is 987654321
123456789 is my Mobile
Mobile number is 776655881

Upvotes: 1

Views: 69

Answers (1)

ggorlen
ggorlen

Reputation: 56875

The pattern "(LandLine|Mobile)\\D*\\d{9}|\\d{9}.*?(LandLine|Mobile)" seems to fit the bill:

import java.util.Arrays;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        var line = "i'm Joe my LandLine number is 987654321, another number 123456789 is my Mobile and wife Mobile number is 776655881";
        var pattern = "(LandLine|Mobile)\\D*\\d{9}|\\d{9}.*?(LandLine|Mobile)";
        var res = Pattern
            .compile(pattern)
            .matcher(line)
            .results()
            .map(MatchResult::group)
            .toArray(String[]::new);
        System.out.println(Arrays.toString(res));
    }
}

Output:

[LandLine number is 987654321, 123456789 is my Mobile, Mobile number is 776655881]

This adds a lazy quantifier ? to .*? along with some minor semantic optimizations like \\D instead of [^\\d].

Upvotes: 2

Related Questions