oracle regexp yeteneklerini kullanarak to_date fonksiyonunda hata verecek tarihleri önceden tespit edip hataya düşmeden null olarak dönmesini sağladık . önce fonksiyonu  vereyim sonrasında bi cümlem daha olacak (:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
CREATE OR REPLACE FUNCTION to_date2(txt IN VARCHAR2,Format IN Varchar2:='DD.MM.YYYY')
   RETURN VARCHAR2
IS
   Gun   INT;
   Ay    INT;
   Yil   INT;
BEGIN
   IF REGEXP_LIKE (
         txt,
         '(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)\d\d)'
      )
   THEN
      Gun :=
         TO_NUMBER(REGEXP_REPLACE (
                      txt,
                      '(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)\d\d)',
                      '\1'
                   ));
      Ay :=
         TO_NUMBER(REGEXP_REPLACE (
                      txt,
                      '(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)\d\d)',
                      '\2'
                   ));
      Yil :=
         TO_NUMBER(REGEXP_REPLACE (
                      txt,
                      '(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)\d\d)',
                      '\3'
                   ));
 
      IF MOD (Yil, 4) = 0
      THEN
         IF (Ay = 2 AND Gun > 29)
         THEN
            RETURN NULL;
         END IF;
      ELSIF (Ay = 2 AND Gun > 28)
      THEN
         RETURN NULL;
      END IF;
 
      IF (Ay <= 7)
      THEN
         IF (MOD (Ay, 2) = 1 AND Gun > 31) OR (MOD (Ay, 2) = 0 AND Gun > 30)
         THEN
            RETURN NULL;
         END IF;
      ELSIF (Ay > 7)
      THEN
         IF (MOD (Ay, 2) = 0 AND Gun > 31) OR (MOD (Ay, 2) = 1 AND Gun > 30)
         THEN
            RETURN NULL;
         END IF;
      END IF;
      RETURN TO_CHAR (to_date(Gun||'.'||Ay||'.'Yil),Format);
   END IF;
 
   RETURN NULL;
END;
/

bunlar yerine to_date ve to_char fonksiyonlarını içeren bir fonskiyonla hata yakalandığında null dön diyebilirdik . fonksiyonun tek yaptığı 01/10.2009 gibi farklı işaretler kullanıldığında da ayırabilmek (: ama madem bu kadar uğraştım yayınliim dedim (:

iyi çalışmalar

sardım ben iyice  regex ve yorumlama işine. ufacık bir sql yorumlama sınıfı yaptım. henüz herşeyi yapamasa da bir diziden eleman elemek kolay oldu artk :) fazla uzatmadan class içeriini ver örnek adresi veriyorum

Örnek : http://www.tufyta.com/projects/d3linq/

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
<?php
 /**
 * @name        D3Linq | Linq In Php
 * @version     1.0.1 
 * @author      Tufan Barış YILDIRIM
 * @link        htpp://www.tufyta.com
 * @since       20.10.2009
 * v2
 * =====
 * @todo Sql Group Funcs <SUM,AVG,COUNT etc.>
 * v1.0.1
 * ======
 * - Delete Statemend added. Can Delete any object from an array ( global )        
 * v1.0
 * ======
 * - This Class can be used for select from arrays as a sql query
 * - You;
 * - Can use php codes in Where clauses
 * - Can also use alias for key and value
 * - And can select array in array as  arrayname.elementname
 */
    class D3Linq{
 
      public    $OnError;
 
      private   $Index=0,
                $Result=False,
                $ResultKeys=array(),
                $ResultValues=array(),
                $isBasic=False,
                $isComplicated=False,
                $Tokens,
                $ErrorMsg,
                $ErrorCode;
       #Tokens Index
       const    QR_IDNEX    =0,     // Query Index
                ST_INDEX    =1,     // Statement type Index
                AR_INDEX    =7,     // Array name Index
                CL_INDEX    =3,     // Column Index                          
                AL_COUNT    =8,     // Count of matches for a basic query (without WHERE clause)
                WH_COUNT    =13,    // Count Of matches for a complicated query (with WHERE clauses)
                CM_WHINDEX  =12;    // Where clause index when is complicated
 
       # Errors with Codes        
       const    INVALID_SQL         ='010|Invalid SQL',
                MISSING_OPERATORS   ='020|Missing Operators',
                MISSING_P           ='021|Missing %1 parenthesis',
                UNEXCEPTED_ERROR    ='030|Unexcepted "<b><i>%1</i></b>"',
                EXCEPTED_BUT        ='031|Excepted "<b><i>%1</i></b>"  but found "<i>%2</i>"',
                NOT_AN_ARRAY        ='040|%1 is not an array',             
                NOT_AN_INTEGER      ='041|%1 is not an integer value on %2';                 
      /**
      * Constructor
      */
       public function D3Linq(){
            $this->Index=0;
            $this->ErrorMsg='';
            $this->ErrorCode='';
            $this->ResultKeys=array();
            $this->ResultValues=array();
            $this->Result=False;
            $this->isBasic=False;
            $this->isComplicated=False;
            $this->Tokens=array();
       }
 
       /**
       * Main Qery Parser
       * @param mixed $SQL it must be valid sql query string
       */
       public function Query($SQL){
           $this->D3Linq();    
 
           preg_match('/(SELECT|DELETE)([\s]+)([a-zA-Z0-9\s,]+|\*|.*)?([\s]+)?(FROM)([\s]+)([A-Za-z_0-9\.]+)([\s]+)*((WHERE)([\s]+)([^;]+))*/is',$SQL,$this->Tokens);
 
            switch(count($this->Tokens)) {
               case self::WH_COUNT:
               $this->isComplicated=True;
               break;
               case self::AL_COUNT:
               $this->isBasic=True;
               break;
               default:
                $this->Error(self::INVALID_SQL);
               break;
           }
 
              $RpCount=self::CountIn('\)',$this->Tokens[self::QR_IDNEX]);
              $LpCount=self::CountIn('\(',$this->Tokens[self::QR_IDNEX]);
           if($RpCount!=$LpCount) {
               if($RpCount<$LpCount){
                  $this->Error(self::MISSING_P,'right');
               }else{
                   $this->Error(self::MISSING_P,'left');
               }
           }
           switch (strtoupper($this->Tokens[self::ST_INDEX])){
               case 'SELECT':
               $this->Select($this->Tokens);
               break;
               case 'DELETE':
               $this->Delete($this->Tokens);
               break;
               default:
                $this->Error(self::UNEXCEPTED_ERROR,$this->FirstOf(explode(' ',$SQL)));
               break;
           }
 
       }
       /**
       * Set the index of current Row
       *
       * @param mixed $Int
       */
       public function data_seek($Int){
            if(is_numeric($Int)){
                $this->Index=$Int;
            }else {
                $this->Error(self::NOT_AN_INTEGER,array($Int,__FUNCTION__));
            }
       }
       /**
       * Get Unfetched Count
       * @return int
       */
       public  function num_rows(){
           return count($this->ResultKeys)-$this->Index;
       }
       /**
       * Fetch Result As D3Field. Return false if no result.
       * @return D3Object or False
       */
       public function fetch_object(){
           if($Object=$this->fetch_assoc()){
               return  (object)$Object;
           }
           else {
               return false;
           }
       }
       /**
       * Convert the obje name as  arrayname.indname ..to array arrayname[indname]
       *                              
       * @param mixed $dottedObject
       */
       private function dotObjectToArray($dottedObject){
             if(preg_match('/([A-z0-9_\.]+)/',$dottedObject)){
                 $objs=explode('.',$dottedObject);
                 $arrName=$objs[0];
                 global $$arrName;
                 $globalEleman=$$arrName;
 
                 foreach($objs as  $index=>$name){
                    if($index>0){
                          $globalEleman=$globalEleman[$name];
                          $globalName.=$globalname.'['.$name.']';
                      }else {
                          $globalName=$name;
                      }
                 }  
                 if(!is_array($globalEleman)){
                     $this->Error(self::NOT_AN_ARRAY,$dottedObject);
                 }else {
                     return array('array'=>$globalEleman,'global'=>$globalName,'arrName'=>$arrName);
                 }
             }else {
                 $this->Error(self::NOT_AN_ARRAY,$dottedObject);
             }                   
             return $dottedObject;
 
       }
       /**
       * Fetch Result as an Array. return false if not result
       * @return Array or False
       */
       public function fetch_assoc(){
                if($this->ResultKeys[$this->Index] AND $this->ResultValues[$this->Index]){
                    if($this->Tokens[self::CL_INDEX]=='*')  {
                            $Assoc=array('key'=>$this->ResultKeys[$this->Index],'value'=>$this->ResultValues[$this->Index]);
                    }else {
 
                        preg_match_all('/(key|value)((([\s]+)as)?([\s]+)([^,]+))?/i',$this->Tokens[self::CL_INDEX],$ColumnsWithAlias);
                        foreach($ColumnsWithAlias[1] as $colndx=>$colname){
                            $Assoc[trim($ColumnsWithAlias[6][$colndx] ? $ColumnsWithAlias[6][$colndx] : $colname)]=$colname=='key'?$this->ResultKeys[$this->Index]:$this->ResultValues[$this->Index];
                        }
 
                    }
                    $this->Index++;
                    return $Assoc;
                }
                else {
                    return False;
                }
       }
       /**
       * Main Selector Function
       *
       * @param mixed $Matches Tokens.
       */
       private function Select($Matches){
           $getObj=$this->dotObjectToArray($Matches[self::AR_INDEX]);
           $Dizimiz=$getObj['array'];
           if(!is_array($Dizimiz)){
             $this->Error(self::NOT_AN_ARRAY,$Matches[self::AR_INDEX]);
           }
           if($this->isComplicated){
                    $sart=$Matches[self::CM_WHINDEX];
                    $sart=preg_replace('/(key|value)(=|==|<|>|<=|>=)/i','$$1$2',$sart);
                    $Find=array('key=','value=','\'.key.\'','\'.value.\'');
                    $Replace=array('key==','value==','$key','$value');
                    $sart=str_replace($Find,$Replace,$sart);
                    $sart=preg_replace('/(key|value)([\s]+)(LIKE)*([\s]+)(\')*([^\'\n]+)(\')*/i','preg_match(\'/(\'.str_replace(\'%\',\'(.*)\',\'$6\').\')/i\',$$1)',$sart);
               }else {
                   $sart=true;
               }
 
           foreach ($Dizimiz as $key=>$value){
               @eval('$SartSaglandi=('.$sart.');');
             if($this->isBasic || $SartSaglandi){
                  $this->ResultValues[]=$value;
                  $this->ResultKeys[]=$key;
               }
           }                                                            
           return $this;
       }
 
       /**
       * Main Deleter Function
       *
       * @param mixed $Matches Tokens.
       */
       private function Delete($Matches){
           $getObj=$this->dotObjectToArray($Matches[self::AR_INDEX]);
           $Dizimiz=$getObj['array'];
           if(!is_array($Dizimiz)){
             $this->Error(self::NOT_AN_ARRAY,$Matches[self::AR_INDEX]);
           }
           if($this->isComplicated){
                    $sart=$Matches[self::CM_WHINDEX];
                    $sart=preg_replace('/(key|value)(=|==|<|>|<=|>=)/i','$$1$2',$sart);
                    $Find=array('key=','value=','\'.key.\'','\'.value.\'');
                    $Replace=array('key==','value==','$key','$value');
                    $sart=str_replace($Find,$Replace,$sart);
                    $sart=preg_replace('/(key|value)([\s]+)(LIKE)*([\s]+)(\')*([^\'\n]+)(\')*/i','preg_match(\'/(\'.str_replace(\'%\',\'(.*)\',\'$6\').\')/i\',$$1)',$sart);
               }else {
                   $sart=true;
               }
 
           foreach ($Dizimiz as $key=>$value){
               @eval('$SartSaglandi=('.$sart.');');
             if($this->isBasic || $SartSaglandi){   
                 $deleteCode='global $'.$getObj['arrName'].'; unset($'.$getObj['global'].'['.$key.']);';
                 eval($deleteCode);
 
               }else {
                  $this->ResultValues[]=$value;
                  $this->ResultKeys[]=$key;
               }
           }                                                            
           return $this;
       }
 
       /**
       * Error Creating Function
       *
       * @param mixed $String Error Template
       * @param mixed $Vals  Replace Values
       */
       private function Error($String,$Vals=False){
            $ErrAndCode =explode('|',$String);
            $Error      =strip_tags($ErrAndCode[1]);
            $ErrCode    =$ErrAndCode[0];
 
            if(is_array($Vals)) {
                  foreach($Vals AS $key=>$value){
                      $Error=str_replace('%'.($key+1),$value,$Error);
                  }
                }elseif($Vals){
                    $Error=str_replace('%1',$Vals,$Error);
                }
                $this->ErrorP($Error,$ErrCode);
 
       }
       /**
       * Print Error with Code.
       *
       * @param mixed $String  Error Message
       * @param mixed $Code    Error Code
       */
       private function ErrorP($String,$Code=000){
           $this->ErrorMsg  =$String;
           $this->ErrorCode =$Code;
          if($this->OnError)  {
            $this->RunEvent($this->OnError);
          }else{
            echo '<div><b>#'.$Code.'</b> '.$String."</div>\n";
          }
       }
       /**
       * Return First of Given Array
       *
       * @param mixed $Array
       * @return mixed  First of Array Element
       */
       private function FirstOf($Array){
           return $Array[0];
       }
       /**
       * Find Char Count in a string
       *
       * @param mixed $Needle 
       * @param mixed $Haystack
       * @return int  Char Count
       */
       private function CountIn($Needle,$Haystack){
                 preg_match_all('/([^\\\]['.$Needle.'])/i',$Haystack,$Found);
                 return count($Found[1]);
       }
       /**
       * Event Runner
       *
       * @param mixed $EventName Func Name
       * @param mixed $Param  Func Param(s)
       * @return mixed Func Result which called
       */
       private function RunEvent($EventName,$Param=False){
          if(function_exists($EventName)){
              if($Param){
 
               if(is_array($Param)){
                 return call_user_func_array($EventName,$Param); 
 
               } else {
                 return call_user_func($EventName,$Param);
               }
 
              }else {
                 return call_user_func($EventName);
                   }
            }
      }         
      /**
      * Get Last D3Linq Error Message
      * @return String               
      */
      public function ErrorMsg(){
          return $this->ErrorMsg;
      }
      /**
      * GEt Last D3Linq Error Code
      * @return String                           
      */
      public function ErrorCode(){
          return $this->ErrorCode;
      }
 
   }    
 
?>  

Bu aralar regex ile devam ediyorum. bugun oracleda ihtiyacım oldu düzenli ifadelere kullanırken aklıma geldi bloguma da eklim dedim.

Oracle Regex Fonksiyonları : 

Fonksiyon Açıklama
REGEXP_LIKE LIKE gibi çalışır ama katar tanımlamanıza olanak sağlar.
REGEXP_INSTR Katara uyan ilk eşleşmenin ilk karakterinin indisi olarak döner.
REGEXP_REPLACE Klasik Regexp replace işi yapar.
REGEXP_SUBSTR Katara eşleşen metin olarak döner.

 Örnekler :

REGEXP_LIKE :

0
SELECT *FROM HASTALAR WHERE  REGEXP_LIKE(HASTA_ADI,'([A-Z]+)','c');

ilk parametremiz arama yapacağımız alan ya da metnin kendisi, ikincisi katar görüntüsü üçüncü parametremiz de regex ayarları oluyor.

Bu sorgunun sonucunda bize sadece büyük harflerden oluşmuş isimler gelir.

Regex Ayarları: 

Fonksiyon Açıklama
c Büyük küçük harf duyarlı eşleşme (varsayılan)
i Büyük küçük harfe duyarsız eşleşme
n “match-any-character” ayarını açar. (sadece acıkken nokta satır sonu ile de eşleşir)
m multiline ayarı (:

REGEXP_INSTR:

 

0
SELECT REGEXP_INSTR('TUFAN BARIS YILDIRIM 123','([0-9]+)') FROM DUAL

sorgu sonucunda katara ilk eşleşen kısım “123″ olacağından ilk karakterinin yani ” 1″ in indisi  yani 25 sonucunu alırız

REGEXP_SUBSTR

 

0
SELECT REGEXP_SUBSTR('TUFAN BARIS YILDIRIM 123','([0-9]+)') FROM DUAL

sorgu sonucunda katara ilk eşleşen kısım “123″ olacağından bize 123 olarak döner. ilk eşleşmeden sonrakileri almak istiyorsak regexp_replace kullanrız.

REGEXP_REPLACE

 

0
SELECT REGEXP_REPLACE('TUFAN BARIS YILDIRIM 123','([A-Z]+)([\s]+)([0-9]+)','rakamlardan onceki son kelime : \1') FROM DUAL

sorguda ilk önce katarı  inceleyelim  3 gruptan oluşuyor ilk grubumuz büyük harf(ler) ikincisi boşluk(lar) üçüncü grubumuz rakam(lar) replace işleminde kullandığımız \1  eşleşen grubun indisin belirtir bulduğumuz sonucu ilk grup ile değiştirip cıktı olark alıyoruz.  eşleşen grup  “YILDIRIM 123″  olur  replace işleminde  ilk grubu yerine yazarsak bize
“rakamlardan önceki son kelime : YILDIRIM” diye döner.

bi dahaki regex ya da oracle yazımızda görüşürz inş  iyi çalışmalar..

regexper.exe küçük birşey gibi görünse de buna daha yapılacak çook şey olduğuna inanıyorum. yazdığınız metinde regexp ile replace özelliği “phpdeki preg_replace  fonksiyonu gibi” ekledim yine renklerle destekledim her katar grubu için bir renk ve onu temsil eden sıra numarasıyle ” $1 gibi” istediğiniz replace olayını yaptırabilirisiniz.

 

Resme Tıklayarak yeni sürümü indirebilirsinizRegexp Replace

© 2012 Tufan Suffusion theme by Sayontan Sinha