开发者

How to write regular expression to find one or more digits separated by periods without returning the last period?

How to write regular expression to find between one and three digits separated by periods without returning the last period? For example, find the string

1.1.

and it would also need to match

1.1

or si开发者_运维百科mply

1

Likewise, it needs to support between one and three digits, so

11.11.11

and

111.111.111

need to work as well.

So..the string won't always end with a period, but it may. Further, if it does end with a period, don't return the last period (so, using a positive lookahead). So, 1.1. if matched would return 1.1

Here is what I have so far, but I am struggling to find a way to NOT return the last period:

(\d{1,3}\.?)+(?=(\Z|\s|\-|\;|\:|\?|\!|\.|\,|\)))

It is returning

6.6.

but I want it to return

6.6


You require: match d.d.d.d. or d.d.dxxx, and regardless of whether it ends with a "." or not, always stop at the last d (never the dot).

What's wrong with just: (\d(\.\d)*)

If you want your dotted-digit string to be terminated by a set of characters, put a look-ahead after it, as you have in your question:

(\d(\.\d)*)(?=(\Z|\s|\-|\;|\:|\?|\!|\.|\,|\)))

If you also want it to match a stand-alone string (with or without the terminator), add a ? after the look-ahead:

(\d(\.\d)*)(?=(\Z|\s|\-|\;|\:|\?|\!|\.|\,|\)))?

For more than one digits, just replace \d with \d{1,3} etc.


The regex (\d{1,3}(?:\.\d{1,3})*)\.{0,1} should work.

In the Group 1 (if taken Group 0 as the entire match) will be stored the string you want to keep, without the . at the end, in case it contains it.

It basically does:

  • Start matching 1-3 digits
  • Then match strings like .d, .dd, or .ddd
  • If the match ends with a ., it won't take it because it isn't inside the group.

Do your tests and let us know if it works with all your examples.

Edit:

Replace + with *


/\d{1,3}(\.\d{1,3})*/

Quick explanation:

\d{1,3}  # Match 1-3 digits
(        # Start Capture Group 1
  \.       # Match '.'
  \d{1,3}  # Match 1-3 digits
)*       # End Capture Group 1 - match 0 or more times


You can write your own Regular expression and test with dummy data on following Site:

http://myregexp.com/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜