Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4418

Regex for find data

I have used this (?:#\d{7}) regex for extracting only 7 digit after '#'.

For example I have string something like "#1234567890". After using the above patterrn I will get 7 digit after '#'.

Now the problem is : I have string something like that "Referenc number #1234567890" where "Referenc number #" fixed.

Now I am finding for regex which can return the 1234567 number from the above string. I have a one file which contains above string and there are also other data available.

Upvotes: 0

Views: 66

Answers (3)

Sarthak Mittal
Sarthak Mittal

Reputation: 6104

You can try something like this:

    String ref_no = "Referenc number #123456789";
    Pattern p = Pattern.compile("Referenc number #([0-9]{7})");
    Matcher m = p.matcher(ref_no);
    while (m.find())
    {
        System.out.println(m.group(1));
    }

Upvotes: 1

Hendrik Simon
Hendrik Simon

Reputation: 231

If the String always starts with Referenc number # you could just use the following code:

String text = "Referenc number #1234567890";
Pattern pattern = Pattern.compile("\\d{7}");
Matcher matcher = pattern.matcher(text);

while(matcher.find()){
    System.out.println(matcher.group());
}

Upvotes: 0

Joakim Platbarzdis
Joakim Platbarzdis

Reputation: 1

The ?: should make your group "non-capturing", so if you add that separately around the hash sign, it should used for matching but excluded from capture.

(?:#)(\d{7})

Upvotes: 0

Related Questions