简体   繁体   English

正则表达式匹配特定位置的数字

[英]regex to match numbers in specific location

I want to match a string using regex, the string I wanna match is xxxxx_S_xxxxxx (where x are numbers), I want to match the three numbers closer to S to the left and the four numbers closer to the right.我想使用正则表达式匹配一个字符串,我想匹配的字符串是xxxxx_S_xxxxxx (其中 x 是数字),我想匹配左边靠近S的三个数字和右边靠近 S 的四个数字。

Let's say I have c1123_S_1234 so I want to match 123_S_1234假设我有c1123_S_1234所以我想匹配123_S_1234

This is what I tried:这是我试过的:

(^[0-9]{3}$+_S_[0-9])

but it's not working, not matching anything, any suggestions?但它不起作用,不匹配任何东西,有什么建议吗?

Regex engine parses the text from left to right, ie it checks the position at the start of string for a match first, if it does not match, it goes on to the right and checks the rest of the string. Regex 引擎从左到右解析文本,即首先检查字符串开头的 position 是否匹配,如果不匹配,则继续向右检查字符串的 rest。 The pattern sequences are also parsed from left to right, if you have (^[0-9]{3}$+_S_[0-9]) , first, the ^ will be checked, ie the start of string.模式序列也从左到右解析,如果你有(^[0-9]{3}$+_S_[0-9]) ,首先,将检查^ ,即字符串的开头。 And as there is only one start of string, the regex could potentially only match at the start of string, but the $ end of string anchor presence in the middle of the regex makes it a pattern that matches no string.由于只有一个字符串开头,正则表达式可能只匹配字符串的开头,但是正则表达式中间的$字符串锚点结尾使其成为不匹配任何字符串的模式。

That means you can't tell the regex engine to find a _S_ substring and then start consuming text to the right or left.这意味着您无法告诉正则表达式引擎找到_S_ substring 然后开始使用右侧或左侧的文本。

You need你需要

[0-9]{3}_S_[0-9]{4}
\d{3}_S_\d{4}

See the regex demo .请参阅正则表达式演示 [0-9]{3} searches for three consecutive digits, then there must be _S_ right after, and then any four digits must follow. [0-9]{3}搜索三个连续的数字,然后后面必须有_S_ ,然后必须是任何四个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM