I'm trying to create a regex pattern for my powershell code. I've never worked with regex before, so I'm a total noob.
我正在为我的powershell代码创建一个regex模式。我以前从来没有和regex合作过,所以我是一个新手。
The regex should check if there are two points in the string.
regex应该检查字符串中是否有两个点。
Examples that SHOULD work:
例子应该工作:
3.1.1
5.10.12
10.1.15
Examples that SHOULD NOT work:
不应该起作用的例子:
3
3.1
5.10.12.1
The string must have two points in it, the number of digits doesn't matter.
字符串中必须有两个点,数字的数量无关紧要。
I've tried something like this, but it doesn't really work and I think its far from the right solution...
我尝试过这样的方法,但并不奏效,我认为这远远不是正确的解决方法。
([\d]*.[\d]*.[\d])
2 个解决方案
#1
2
In your current regex I think you could escape the dot \.
or else the dot would match any character.
在您当前的regex中,我认为您可以避免使用点\。否则点会匹配任何字符。
You could add anchors for the start ^
and the end $
of the string and update your regex to ^\d*\.\d*\.\d*$
That would also match ..4
and ..
您可以添加锚开始^和$的字符串和更新你的regex ^ \ d * \ \ d * \。还可以匹配……4 . .
Or if you want to match one or more digits, I think you could use ^\d+(?:\.\d+){2}$
或者如果你想匹配一个或多个数字,我认为你可以用^ \ d +(?:\ \ d +){ 2 } $
That would match
这将匹配
^ # From the beginning of the string \d+ # Match one or more digits (?: # Non capturing group \.\d+ # Match a dot and one or more ditits ){2} # Close non capturing group and repeat 2 times $ # The end of the string
#2
1
Use a lookahead:
使用一个超前:
^\d(?=(?:[^.]*\.[^.]*){2}$)[\d.]*$
Broken down, this says:
^ # start of the line
\d # at least one digit
(?= # start of lookahead
(?:[^.]*\.[^.]*){2} # not a dot, a dot, not a dot - twice
$ # anchor it to the end of the string
)
[\d.]* # only digits and dots, 0+ times
$ # the end of the string
See a demo on regex101.com.
#1
2
In your current regex I think you could escape the dot \.
or else the dot would match any character.
在您当前的regex中,我认为您可以避免使用点\。否则点会匹配任何字符。
You could add anchors for the start ^
and the end $
of the string and update your regex to ^\d*\.\d*\.\d*$
That would also match ..4
and ..
您可以添加锚开始^和$的字符串和更新你的regex ^ \ d * \ \ d * \。还可以匹配……4 . .
Or if you want to match one or more digits, I think you could use ^\d+(?:\.\d+){2}$
或者如果你想匹配一个或多个数字,我认为你可以用^ \ d +(?:\ \ d +){ 2 } $
That would match
这将匹配
^ # From the beginning of the string \d+ # Match one or more digits (?: # Non capturing group \.\d+ # Match a dot and one or more ditits ){2} # Close non capturing group and repeat 2 times $ # The end of the string
#2
1
Use a lookahead:
使用一个超前:
^\d(?=(?:[^.]*\.[^.]*){2}$)[\d.]*$
Broken down, this says:
^ # start of the line
\d # at least one digit
(?= # start of lookahead
(?:[^.]*\.[^.]*){2} # not a dot, a dot, not a dot - twice
$ # anchor it to the end of the string
)
[\d.]* # only digits and dots, 0+ times
$ # the end of the string
See a demo on regex101.com.