简体   繁体   中英

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.

RegEx Match Conditions 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.

EDIT

I would indeed prefer to do away with the RegEx in this case but I am not the original author of the app. 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. 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); $2 is the matched 12 chars.

$3 is the entire match for the second case (32 chars long); $4 is the matched 12 chars.

Easy!

The other, and arguably easier, way, is to look at the inbound string and assign the correct regex instance based on string length:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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