user1194310
user1194310

Reputation: 129

Need Regex to match a String

I am new to Java. I need a regex to match string with such a pattern:

[0-9].[0-9].[0-9]

For example, the regex should match strictly 5.5.0 or 4.6.5 or 5.2.2.

The above pattern matches strings like 135.9.0 which will give output as 5.9.0

But I do not want to match such kind of pattern.

I should be able to match exactly three digits which is separated by a period(.) symbol.

Upvotes: 2

Views: 179

Answers (5)

Rohit Jain
Rohit Jain

Reputation: 213361

Below Regex will do what you want: -

\b\d+\.\d+\.\d+\b
  • \d matches any digit.

If you just want to match single digit separated by . you can use: -

\b\d\.\d\.\d\b
  • \b is for boundary checking..

Try this code: -

String str = "5.0.0 abc 5.6.7 abc 12.45.65 From: 133.5.0<pos1.002otak.com>";

Pattern pattern = Pattern.compile("\\b\\d\\.\\d\\.\\d\\b"); 
Matcher match = pattern.matcher(str);

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

OUTPUT

5.0.0
5.6.7
// 12.45.65 is not printed

UPDATE: -

To match 1.4.5 inside abc1.4.5def and not in 121.4.546 use the below pattern: -

[^\\d](\\d\\.\\d\\.\\d)[^\\d]

Upvotes: 1

Anirudha
Anirudha

Reputation: 32817

This regular expression will do

\b\d\.\d\.\d\b

\d matches a digit i.e 0-9

. need to be escaped with \ else it would match any character

Upvotes: 1

Didi Kohen
Didi Kohen

Reputation: 560

You should escape your dots with a backslash since a dot matches every character in regular expressions.
You should add a caret (^) at the beginning and a dollar sign at the end of the regex to limit the matching to the entire string and not part of it (which may match if the string has things you do not want).

^[0-9]\.[0-9]\.[0-9]$

Or match a predefined prefix/suffix, or a non number in the beginning by using (this is only if you the string may have something other than a number in the beginning, otherwise use the above):

[^0-9]

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57690

As . is a meta-character in regular expression, escape it like \.. Hence the expression,

[0-9]\.[0-9]\.[0-9]

This can be simplified to

\d\.\d\.\d

or even to

(\d\.){2}\d

This will match any 3 digits separated by a ..

Also note if you want to extract 5.9.0 from "string 5.9.0" then use the regex above. But if you want to match 5.9.0 from exactly "5.9.0" (the whole string, used in some kind of validation) they you should use ^ at the start and $ at the end. So it'll be something like

^(\d\.){2}\d$

Lastly (as your question is quite unclear whether you want to match single digit or a sequence of digits), to match sequence of digit use [0-9]+ instead of [0-9] or \d+ instead of \d.

Upvotes: 3

Yossi
Yossi

Reputation: 12110

You can use either:

^\d\.\d.\d$

Or

\b\d\.\d.\d\b

Upvotes: 1

Related Questions