正则表达式条件语句(如果字符串有一定的开头,则只解析数字)

时间:2014-03-13 07:36:50

标签: regex if-statement conditional

首先我使用了一个返回我的relaystates的字符串,因此“1.0.0.0.1.1.0.0”将被解析/分组为\ d +, 然后我的八个开关使用'格式响应',例如{1}获取每个开关的状态。

现在我需要从这个字符串中获取数字:“RELAYS.1.0.0.0.1.1.0.0”

\ d +仍会得到数字,但我只想得到它们,如果字符串以“RELAYS”开头

任何人都可以解释我是如何做到的吗?

提前一百万! 编辑冰熊(今天00:24)

1 个答案:

答案 0 :(得分:1)

使用.NET引擎,您可以使用正则表达式(?<=^RELAYS[\d.]*)\d+。但是大多数正则表达式引擎都不支持negative lookbehind assertion中的无限重复。

live on regexhero.net

<强>说明:

(?<=     # Assert that the following can be matched before the current position:
 ^RELAYS # Start of string, followed by "RELAYS"
 [\d.]*  # and any number of digits/dots.
)        # End of lookbehind assertion
\d+      # Match one or more digits.

使用PCRE引擎,您可以使用(?:^RELAYS\.|\G\.)(\d+)并为每场比赛访问第1组。

live on regex101.com

<强>说明:

(?:        # Start a non-capturing group that matches...
 ^RELAYS\. # either the start of the string and "RELAYS."
|          # or
 \G\.      # the position after the previous match, followed by "."
)          # End of non-capturing group
(\d+)      # Match a number and capture it in group 1