user5781295
user5781295

Reputation:

Java REGEX Pattern Problems

I'm working on a call record app ,I had a problem that my pattern was not matching but i solved that.Still the solution is not the best.

String subject = "d20160812215452p38762620479tincomingmfalse.3gp";

String pattern = "^d[\\d]{14}p[\\d]{11}t[\\w]{8}m[\\w]*\\.3gp";

if(subject.matches(pattern)){
    System.out.print("Matching");
}else{
    System.out.print("Not maching");
}

The problem is that the phone number String subject****p38762620479**** might be bigger than 8 characters ,also how could i split the pattern that it shows: the date,number.....

Upvotes: 0

Views: 77

Answers (2)

ItamarBe
ItamarBe

Reputation: 490

Adding to @kolboc's answer, in order to get the groups you matched, do this:

String subject = "d20160812215452p38762620479tincomingmfalse.3gp";
String pattern = "^d([\\d]{14})p([\\d]{11})t([\\w]{8}m[\\w]*\\.3gp)";
Pattern r = Pattern.compile(pattern);

// create a matcher object
Matcher m = r.matcher(subject);
if (m.find( )) {
   System.out.println("Found all: " + m.group(0) );
   System.out.println("Found date: " + m.group(1) );
   System.out.println("Found phone: " + m.group(2) );
   System.out.println("Found title: " + m.group(3) );
} else {
   System.out.println("NO MATCH");
}

Upvotes: 1

kolboc
kolboc

Reputation: 825

To catch the date, number, etc. You need to group your regex into groups, e.g.: String: 555666 catcat to match number and word you would write (\d+)\s(\w+), there I got first group with number and second with word.

So in your example if you want to catch sequence of numbers then address you would use: "^d([\\d]{14})p([\\d]{11})t([\\w]{8}m[\\w]*\\.3gp)". To say pattern that something may be bigger than 8 characters you can use range like {8, 10} - that says at least 8 characters, but max 10, or simply {8,} meaning it will be at least 8 characters.

Upvotes: 1

Related Questions