tags:

views:

116

answers:

4

I want to match "81" in "630.81.11". I'm stuck with \.[0-9]*\. which includes the dots.

+10  A: 
/^[0-9]+\.([0-9]+)\.[0-9]+$/
Coronatus
+1: Assuming PCRE, of course.
Chris
+6  A: 

Update: After seeing what problem you are trying to solve, I would suggest not using regular expressions.

Its for use in a PostGreSQL query. I need to sort by the three parts. Something like:

ORDER BY
    substring(plannr from '^[0-9]*')::integer,
    substring(plannr from '\.[0-9][0-9]\.')::interger,
    substring(plannr from '[0-9]*$')::integer

Instead of using a regular expression you can use for example split_part:

SELECT plannr
FROM table1
ORDER BY
    split_part(plannr, '.', 1)::integer,
    split_part(plannr, '.', 2)::integer,
    split_part(plannr, '.', 3)::integer;

Result:

"2.2.3"
"2.10.3"
"2.10.20"
"10.1.4"
"630.81.11"

Test data:

CREATE TABLE table1 (plannr VARCHAR(100) NOT NULL);
INSERT INTO table1 (plannr) VALUES
('630.81.11'),
('2.2.3'),
('2.10.3'),
('2.10.20'),
('10.1.4');

Original answer: If your regular expression engine includes fixed length lookaheads and lookbehinds you can do this:

(?<=\.)[0-9]+(?=\.)
Mark Byers
+2  A: 

You can enclose the interesting part in a group, and later extract it. So, something like "\.([0-9]*)\."; the parens denote a group.

pelotom
+1  A: 
        Pattern pat = Pattern.compile("\\.(\\d+)\\.");
        String str = "630.81.11";
        Matcher matcher = pat.matcher(str);

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

I've tested it in Java. The output is as follows:

81

npinti