0
点赞
收藏
分享

微信扫一扫

vbscript 字符串处理一例


此例子源于csdn网友在讨论区的一个问题。此问题的大概意思就是有一个字符串,由三部分组成:

z=z1 + z2 + z3

让大家写一个代码将 z2 从 z 中取出来。

生成z的代码如下:

 

Randomize 
   
x1 
  = 
  int 
  ( 
  rnd 
  () 
  * 
  9 
  )  
  + 
  1 
  
 
  Randomize 
   
x2 
  = 
  ( 
  int 
  ( 
  rnd 
  () 
  * 
  9 
  )  
  + 
  1 
  ) 
  * 
  2 
  - 
  1 
  
 
  Randomize 
   
x3 
  = 
  int 
  ( 
  rnd 
  () 
  * 
  9 
  )  
  + 
  1 
  

 
  for 
   i 
  = 
  1 
    
  to 
   x1
     
  Randomize 
   
    y1 
  = 
  int 
  ( 
  rnd 
  () 
  * 
  99999 
  )  
  + 
  1 
  
    z1 
  = 
  z1 
  & 
  " 
  [ 
  " 
  & 
  y1 
  & 
  " 
  ] 
  " 
  
 
  next 
  


 
  for 
   i 
  = 
  1 
    
  to 
   x2
     
  Randomize 
   
    y2 
  = 
  int 
  ( 
  rnd 
  () 
  * 
  99999 
  )  
  + 
  1 
  
     
  if 
   i  
  mod 
    
  2 
    
  = 
    
  0 
    
  then 
  
        z2 
  = 
  z2 
  & 
  " 
  [ 
  " 
  & 
  y2 
  & 
  " 
  ] 
  " 
  
     
  else 
  
        z2 
  = 
  z2 
  & 
  y2
     
  end 
    
  if 
  
 
  next 
  


 
  for 
   i 
  = 
  1 
    
  to 
   x3
     
  Randomize 
   
    y3 
  = 
  int 
  ( 
  rnd 
  () 
  * 
  99999 
  )  
  + 
  1 
  
    z3 
  = 
  z3 
  & 
  " 
  [ 
  " 
  & 
  y3 
  & 
  " 
  ] 
  " 
  
 
  next 
  

z 
  = 
  z1 
  & 
  z2 
  & 
  z3 
此代码生成的字符串的规则如下:
z1 和 z3 是由 1到n 个 格式为  [??]的串组成
z2  是类似 ???[???]???   格式的字符串 ,其中 [???]部分的个数 比 ???部分个数 少一个,并且是这样交叉的形式 :一个????  一个 [???]  。??部分至少一个。他们格式如下:
z1=n个[??]      (n>=1) '  
z3=n个[??]      (n>=1)z2=那个 QM       (n>=1)
Q=n个 ??[??]  (1>=n>=0)
M=1个 ??

 

解决代码:

一,不用正则:

 

function    trim_ns(strSource)
   str   = 
  strSource
      do 
    
  while 
  (str 
  <> 
  "" 
  )
      pos1   = 
  instr 
  (str, 
  " 
  ] 
  " 
  )
         if 
  (pos1 
  > 
  0 
  )  
  then 
  
         str   = 
  mid 
  (str,pos1 
  + 
  1 
  )
            if 
    
  left 
  (str, 
  1 
  ) 
  <> 
  " 
  [ 
  " 
    
  then 
    
  exit 
    
  do 
  
         end 
    
  if 
  
      loop 
  
      do 
    
  while 
  (str 
  <> 
  "" 
  )
      pos1   = 
  instrRev 
  (str, 
  " 
  [ 
  " 
  )
         if 
  (pos1 
  > 
  0 
  )  
  then 
  
         str   = 
  left 
  (str,pos1 
  - 
  1 
  )
            if 
    
  right 
  (str, 
  1 
  ) 
  <> 
  " 
  ] 
  " 
    
  then 
    
  exit 
    
  do 
  
         end 
    
  if 
  
      loop 
  
   trim_ns   = 
  str
   end function 
  
response.Write trim_ns(z) 
 
二,用正则:
 
 
   
function    trim_ns(strSource)
       dim    re
       set    re 
  = 
  new 
   RegExp
    re.Global   =   true 
  
    re.IgnoreCase   =   true 
  
    re.MultiLine   =   false 
  
    re.Pattern   =   " 
  .*?](([^[].*][^[].*?)|([^[].*?))[.* 
  " 
  
    trim_rs   =   re.Replace(strSource, 
  " 
  $1 
  " 
  )
       set    re 
  = 
  nothing 
  
   end function   
response.write trim_ns(z)

这个问题其实很简单,之所以发出来,是因为开始的时候我写了3个正则都失败了。最后放弃了,然后用字符串处理的常规方法解决的。但是另一个网友用正则解决的。我一阅读发现。自己的正则水平实在是太差了,这么简单的正则式都没有写对。惭愧!

举报

相关推荐

0 条评论