[英].NET regular expression to extract 1-4 digit value from mixed character value
What I am trying to accomplish a .NET regular expression for the following strings:我正在尝试为以下字符串完成 .NET 正则表达式:
Example 1. abc1234abc - 1234示例 1. abc1234abc - 1234
Example 2. abc12345abc - no results示例2.abc12345abc -没有结果
Example 3. abc1234abc12345 - 1234示例 3. abc1234abc12345 - 1234
I am trying to extract a 1-4 numeric ( 1
, 12
, 123
, or 1234
) from any mixed character value but no more than 4 digits (IE. NOT 12345
).我试图从任何混合字符值中提取 1-4 个数字( 1
、 12
、 123
或1234
),但不超过 4 位(即,不是12345
)。
The [0-9]{1,4}
pattern yields: [0-9]{1,4}
模式产生:
Example 1. abc1234abc - 1234 (good)示例 1. abc1234abc - 1234(好)
Example 2. abc12345abc - 1234, (should return no results)示例 2. abc12345abc - 1234,(不应返回任何结果)
Example 3. abc1234abc12345 - 1234, 1234, 5 (should return ONLY 1234)示例 3. abc1234abc12345 - 1234, 1234, 5(应仅返回 1234)
What am I missing?我错过了什么? Thank you for the help, I am very much new to regular expressions and I could not find what I am looking for anywhere.谢谢你的帮助,我对正则表达式很陌生,我在任何地方都找不到我要找的东西。 I hope my question makes sense.我希望我的问题是有道理的。
You are missing the lookarounds that will check the number is not enclosed with more digits:您缺少将检查数字是否包含更多数字的环视:
(?<!\d)\d{1,4}(?!\d)
Or (if you need to only match regular digits excluding all Uncide ones in Hindi, etc.):或者(如果您只需要匹配不包括印地语中所有 Uncide 数字等的常规数字):
(?<![0-9])[0-9]{1,4}(?![0-9])
See regex demo见正则表达式演示
The (?<!\\d)
is a negative lookbehind that checks if the next subpattern is not preceded with some other subpattern (looks before the current position, "looks behind"), and (?!\\d)
is a negative lookahead that makes sure that there is no digit after the current position ("looks ahead"). (?<!\\d)
是一个否定的lookbehind,它检查下一个子模式之前是否没有其他子模式(在当前位置之前,“looks behind”),并且(?!\\d)
是一个否定的lookahead确保当前位置后没有数字(“向前看”)。 Lookarounds do not consume characters, they just check and then return true or false (thus allowing or failing a match), so, you only get your expected match as a result. Lookarounds 不消耗字符,它们只是检查然后返回 true 或 false(从而允许或失败匹配),因此,您只能得到预期的匹配结果。
More details on regex lookarounds at regular-expressions.info有关正则表达式环视的更多详细信息,请访问regular-expressions.info
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.