简体   繁体   English

RegEx根据字符串长度匹配不同的子字符串

[英]RegEx to match different substrings based on string length

I'm looking for a regular expression to match an alphanumeric string. 我正在寻找一个正则表达式来匹配字母数字字符串。 If the string is 32 characters long, match characters 17 to 28. If the string is 34 characters long, match the last 12 characters. 如果字符串长度为32个字符,则匹配字符17至28。如果字符串长度为34个字符,则匹配最后12个字符。

RegEx Match Conditions http://s12.postimage.org/ghathiz2l/Screen_shot_2012_08_09_at_11_52_22_PM.png RegEx匹配条件http://s12.postimage.org/ghathiz2l/Screen_shot_2012_08_09_at_11_52_22_PM.png

I have two separate expressions to get matches for the two different conditions. 我有两个单独的表达式来获取两个不同条件的匹配。

.(?<match>[0-9]{16}) and .(?<match>[0-9]{12})

In the code, I read the expressions right to left, handle the 'if' and truncate the last 4 characters of the match when the original string is 32 characters long but would like to be able to do this from a single RegEx. 在代码中,我读取了从右到左的表达式,处理了“ if”,并在原始字符串长32个字符时截断了匹配的最后4个字符,但希望能够通过一个RegEx做到这一点。

EDIT 编辑

I would indeed prefer to do away with the RegEx in this case but I am not the original author of the app. 在这种情况下,我确实希望取消RegEx,但我不是该应用程序的原始作者。 The string-parsing conditions may change over time so it is simpler to maintain the RegEx in the config file than to make a new release in this instance. 字符串解析条件可能会随时间变化,因此在这种情况下,在配置文件中维护RegEx比创建新版本要容易得多。 Plus, it's what the boss wants... 另外,这就是老板想要的...

Try this: 尝试这个:

^(.{22}(.{12}))|(.{16}(.{12}).{4})$

$1 is the entire match for the first case (34 chars long); $1是第一种情况的完整匹配项(长34个字符); $2 is the matched 12 chars. $2是匹配的12个字符。

$3 is the entire match for the second case (32 chars long); $3是第二种情况的全部匹配项(长度为32个字符); $4 is the matched 12 chars. $4是匹配的12个字符。

Easy! 简单!

The other, and arguably easier, way, is to look at the inbound string and assign the correct regex instance based on string length: 另一种方法(可能更简单)是查看入站字符串并根据字符串长度分配正确的regex实例:

private static Regex rx34 =  ... ;
private static Regex rx32 = ... ;
string foo( string s )
{
  Regex rx ;

  switch ( s.Length )
  {
  case 34 : rx = rx34 ; break ;
  case 32 : rx = rx32 ; break ;
  default : throw new ArgumentOutOfRangeException("s") ;
  }
  Match m = rx.Match(s) ;
  if ( !m.Success ) throw new InvalidOperationException() ;

  ... // return the appropriate part of the string.

}

Or, why use the regex at all? 或者,为什么要完全使用正则表达式? This isn't a problem for a regex. 对于正则表达式而言,这不是问题。

string foo( string s )
{
  string s12 ;
  switch (( s ?? "" ).Length)
  {
  case 34 : return s12 = s.Substring( 34 - 12 ) ;
  case 32 : return s12 = s.Substring( 16 , 12 ) ;
  default : throw new ArgumentOutOfRangeException("s");
  }
  return s12 ;
}

Because life is too hard to make things more difficult than they are. 因为生活太困难了,所以事情变得比实际困难。

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

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