Tag Archives: regex

Validate an E-Mail Address with PHP

From ILoveJackDaniel’s

function check_email_address($email) {
  // First, we check that there's one @ symbol,
  // and that the lengths are right.
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters
    // in one section or wrong number of @ symbols.
    return false;
  }
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
    if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
      return false;
    }
  }
  // Check if domain is IP. If not,
  // it should be valid domain name
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}

Tags: ,

Renombrar recursivamente archivos y directorios

El siguiente script de bash renombra archivos y directorios convirtiendo sus nombres a minúsculas, reemplazando espacios, acentos, eñes y eliminando paréntesis.

Por defecto renombra únicamente aquellos archivos y directorios ubicados en el directorio pasado como parámetro. Es posible usar la opción-r|--recursivepara que trabaje recursivamente en todos los directorios hijos:

./rename.sh -r dir

Usando la opción-v|--verbosees posible ver en pantalla el listado de archivos modificados

./rename.sh -v -r dir

La opción-t|--testmuestra un listado de cambios a realizar sin realizar ninguno

./rename.sh -t -r dir

Ejemplo

xleo@calcifer:/tmp/music$ rename -t -r .
/tmp/music/Jaime Roos/1998 - Concierto Aniversario
./17 - Amándote.mp3 ./17_-_amandote.mp3
./02 - Victoria Abaracón.mp3 ./02_-_victoria_abaracon.mp3
./12 - Nadie Me Dijo Nada.mp3 ./12_-_nadie_me_dijo_nada.mp3
./16 - Durazno Y Convención.mp3 ./16_-_durazno_y_convencion.mp3
./01 - Si Me Voy Antes Que Vos-1.mp3 ./01_-_si_me_voy_antes_que_vos-1.mp3
./03 - El Hombre De La Calle.mp3 ./03_-_el_hombre_de_la_calle.mp3
./05 - Las Luces Del Estadio.mp3 ./05_-_las_luces_del_estadio.mp3
./07 - Piropo.mp3 ./07_-_piropo.mp3
./10 - Esta Noche.mp3 ./10_-_esta_noche.mp3
./06 - Se Va La Murga.mp3 ./06_-_se_va_la_murga.mp3
./08 - Los Futuros Murguistas.mp3 ./08_-_los_futuros_murguistas.mp3
./15 - Tal Vez Cheché.mp3 ./15_-_tal_vez_cheche.mp3
./13 - Bienvenido.mp3 ./13_-_bienvenido.mp3
./1998 - Concierto Aniversario.m3u ./1998_-_concierto_aniversario.m3u
./09 - Los Olímpicos.mp3 ./09_-_los_olimpicos.mp3
./11 - Cometa De La Farola.mp3 ./11_-_cometa_de_la_farola.mp3
./04 - Cuando Juega Uruguay.mp3 ./04_-_cuando_juega_uruguay.mp3
./14 - El Tambor.mp3 ./14_-_el_tambor.mp3
/tmp/music/Jaime Roos
./1998 - Concierto Aniversario ./1998_-_concierto_aniversario
/tmp/music
./Jaime Roos ./jaime_roos

rename.sh

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
#!/bin/bash
#
# @autor   Leonardo Vidarte
# @version $Id rename.sh 5 2008-06-05 15:44:45Z xleo $
#


# ********
# INIT SET
# ********
verbose=0
recursive=0
MOVE=/bin/mv
ECHO=


# ****
# HELP
# ****
help () {
cat << END
Usage : rename [-t] [-v] [-r] directory

Options:
  -v, --verbose    verbose move
  -r, --recursive  recursive rename
  -t, --test       don't move, only show change list. Implies -v.
  -?, --help       show this help

END

}


# ***************
# RENAME FUNCTION
# ***************
rename () {
   
    find -maxdepth 1 | \
    awk '{out=tolower($0); \
    gsub(" ?\& ?","_y_",out); \
    gsub("\(|\)","-",out); \
    gsub("[\340-\345]","a",out); \
    gsub("\347","c",out); \
    gsub("[\350-\353]","e",out); \
    gsub("[\354-\357]","i",out); \
    gsub("\361","n",out); \
    gsub("[\362-\366]","o",out); \
    gsub("[\371-\374]","u",out); \
    gsub("[^0-9a-z\./_-]","_",out); \
    if ($0!=out) {print "\""$0"\" "out;}}'
| \
    xargs -r -n 2 $ECHO $MOVE

}


# *************
# MAIN FUNCTION
# *************
main () {


    # ----------------
    # Recursive rename
    # ----------------
    if [ $recursive -eq 1 ]; then

        for dir in "$1"/*
        do
            if [ -d "$dir" ]; then
                cd "$dir" && search "$dir"
            fi
        done

    fi


    # ----------------------------
    # Rename files and directories
    # ----------------------------
    if [ $verbose -eq 1 ]; then
        echo "$1"
    fi

    cd "$1" && rename


}


# ***************************
# SHOW HELP WITHOUT ARGUMENTS
# ***************************
if [ $# -eq 0 ]; then
   help
   exit 1
fi


# *********
# SHOW HELP
# *********
if [[ "$1" =~ '(-h|--help)' ]]; then
   help
   exit 0
fi


# ***************
# CHECK ARGUMENTS
# ***************
while [ $# -gt 1 ]; do

    case "$1" in

        -v|--verbose)
            verbose=1
            MOVE="$MOVE --verbose"
        ;;    
        -r|--recursive)
            recursive=1
        ;;
        -t|--test)
            verbose=1
            MOVE=
            ECHO=/bin/echo
        ;;    
        *)
            echo invalid argument $1
            help
            exit 2
        ;;

    esac

    shift

done


# ****************************************
# CHECK DIRECTORY AND INVOKE MAIN FUNCTION
# ****************************************
if [ "$1" == '.' -o "$1" == '*' ]; then
    dir=$PWD
else
    dir=$1
fi

if [ -d "$dir" ]; then
    cd "$dir"
    dir=$PWD
    cd - 1> /dev/null
    main "$dir"
    exit 0
else
    echo rename: directory not found
    exit 3
fi

Otro ejemplo

Salida de./rename -r -v /shared/music > result.txt

Tags: , , ,

Bash Regular Expressions

When working with regular expressions in a shell script the norm is to use grep or sed or some other external command/program. Since version 3 of bash (released in 2004) there is another option: bash’s built-in regular expression comparison operator “=~”.

Bash’s regular expression comparison operator takes a string on the left and an extended regular expression on the right. It returns 0 (success) if the regular expression matches the string, otherwise it returns 1 (failure).

In addition to doing simple matching, bash regular expressions support sub-patterns surrounded by parenthesis for capturing parts of the match. The matches are assigned to an array variable BASH_REMATCH. The entire match is assigned to BASH_REMATCH[0], the first sub-pattern is assigned to BASH_REMATCH[1], etc..

The following example script takes a regular expression as its first argument and one or more strings to match against. It then cycles through the strings and outputs the results of the match process:

#!/bin.bash

if [[ $# -lt 2 ]]; then
    echo "Usage: $0 PATTERN STRINGS..."
    exit 1
fi
regex=$1
shift
echo "regex: $regex"
echo

while [[ $1 ]]
do
    if [[ $1 =~ $regex ]]; then
        echo "$1 matches"
        i=1
        n=${#BASH_REMATCH[*]}
        while [[ $i -lt $n ]]
        do
            echo "  capture[$i]: ${BASH_REMATCH[$i]}"
            let i++
        done
    else
        echo "$1 does not match"
    fi
    shift
done

Assuming the script is saved in “bashre.sh”, the following sample shows its output:

# sh bashre.sh 'aa(b{2,3}[xyz])cc' aabbxcc aabbcc
regex: aa(b{2,3}[xyz])cc

aabbxcc matches
  capture[1]: bbx
aabbcc does not match

Tags: , ,

Librándonos del ^M – mezclando dos y unix

Traducción Getting rid of ^M – mixing dos and unix

Al abrir archivos de otros SO podemos encontrarnos con^Mal final de cada línea:

import java.util.Hashtable; ^M
import java.util.Properties; ^Mimport java.io.IOException;
import org.xml.sax.AttributeList; ^M
import org.xml.sax.HandlerBase; ^Mimport org.xml.sax.SAXException;

/**^M
  * XMLHandler: This class parses the elements contained^M
  * within a XML message and builds a Hashtable^M

Algunos programas no son consistentes en la manera de insertar saltos de línea, entonces te encontrarás con algunas líneas que tienen un salto de línea y un^My algunas que tengan un^My no un salto de línea… con Vim la limpieza se realiza en dos pasos:

1. reemplazar los ^M al final de cada línea:

:%s/^M$//g

Usar"C-v C-m"para escribir^M.

2. reemplazar todos los ^M’s que necesitan un salto de línea:

:%s/^M/n/g

Voila! Archivo limpio.

Mas info en

:help ffs

Tags: , ,

Comfortable editing with VIM

Tomado del blog de Tobias Schlitt

Next occurrence of a word

If you hit*in command mode and your cursor resides on a word, you are taken to the next occurrence of the word. This is quite nice, if you like to know, where a function is called again.

Find matching brace

VIM 7.0 luckily highlights matching parenthesis, if your cursor resides on a brace, but sometimes you need to quickly jump to that matching brace. You can achieve this by hitting the%sign in command mode.

Repeat the last change

It often occurs, that you need to perform 1 change several times, but not often enough to write a short script or to address the changes with a complex regex. In those cases you can perform the change once, move the cursor to the next place and hit the.(dot) char, in command mode.


Read more »

Tags: , ,

Expresiones regulares en MySQL

En MySQL pueden usarse expresiones regulares mediante el operador

REGEXP

:

^

Comienzo de una cadena.

mysql> SELECT 'fo\nfo' REGEXP '^fo$';                   -> 0
mysql> SELECT 'fofo' REGEXP '^fo';                      -> 1

$

Final de una cadena.

mysql> SELECT 'fo\no' REGEXP '^fo\no$';                 -> 1
mysql> SELECT 'fo\no' REGEXP '^fo$';                    -> 0

.

Cualquier caracter (incluído line feed y carriage return).

mysql> SELECT 'fofo' REGEXP '^f.*$';                    -> 1
mysql> SELECT 'fo\r\nfo' REGEXP '^f.*$';                -> 1


Read more »

Tags: ,

Función capitalize

Función capitalize en JavaScript, creada por Jonas Raoni Soares Silva. He cambiado la regex original/\w+/gpor/\S+/gpara que funcione con acentos.

1
2
3
4
5
6
7
8
9
myText = "hElLo wORlD";

String.prototype.capitalize = function() {
    return this.replace(/\S+/g, function(a) {
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

document.write( myText.capitalize() );

Tags: , ,