El siguiente ejemplo muestra un programa estilo grep
: solicita
una expresión regular para aplicarla luego a una serie de entradas
leídas desde la entrada estandar.
casiano@nereida:~/projects/PA/regexp$ cat -n Application.java 1 /** 2 * javac Application.java 3 * java Application 4 */ 5 6 import java.io.*; 7 import java.util.regex.Pattern; 8 import java.util.regex.Matcher; 9 10 public class Application { 11 12 public static void main(String[] args){ 13 String regexp = ""; 14 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 try { 16 System.out.print("Enter your regex: "); 17 regexp = br.readLine(); 18 } catch (IOException e) { System.exit(1); }; 19 while (true) { 20 21 String input = ""; 22 try { 23 System.out.print("Enter input string to search: "); 24 input = br.readLine(); 25 } catch (IOException e) { System.exit(1); }; 26 27 Pattern pattern = Pattern.compile(regexp); 28 Matcher matcher = pattern.matcher(input); 29 30 boolean found = false; 31 while (matcher.find()) { 32 System.out.println("I found the text " 33 + matcher.group() 34 + " starting at index " 35 + matcher.start() 36 + " and ending at index " 37 +matcher.end() 38 ); 39 found = true; 40 } 41 if(!found){ 42 System.out.println("No match found."); 43 } 44 } 45 } 46 }Ejecución:
casiano@nereida:~/Ljavatesting$ java Application Enter your regex: (\d+).(\d+) Enter input string to search: a4b5d6c7efg I found the text 4b5 starting at index 1 and ending at index 4 I found the text 6c7 starting at index 5 and ending at index 8 Enter input string to search: abc No match found. Enter input string to search:
Véase también Java Regular Expressions
Esta es una versión en bash
del conversor de temperaturas
visto en las secciones anteriores:
pl@nereida:~/src/bash$ cat -n f2c 1 #!/bin/bash 2 echo "Enter a temperature (i.e. 32F, 100C):"; 3 read input; 4 5 if [ -z "$(echo $input | grep -i '^[-+]\?[0-9]\+\(\.[0-9]*\)\?\ *[CF]$')" ] 6 then 7 echo "Expecting a temperature, so don't understand \"$input\"." 1>&2; 8 else 9 input=$(echo $input | tr -d ' '); 10 InputNum=${input:0:${#input}-1}; 11 Type=${input: -1} 12 13 if [ $Type = "c" -o $Type = "C" ] 14 then 15 celsius=$InputNum; 16 fahrenheit=$(echo "scale=2; ($celsius * 9/5)+32" | bc -l); 17 else 18 fahrenheit=$InputNum; 19 celsius=$(echo "scale=2; ($fahrenheit -32)*5/9" | bc -l); 20 fi 21 22 echo "$celsius C = $fahrenheit F"; 23 fi
pl@nereida:~/src/regexpr$ cat -n pcregrep.c 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <assert.h> 5 #include <pcre.h> 6 7 char enter_reverse_mode[] = "\33[7m"; 8 char exit_reverse_mode[] = "\33[0m"; 9 10 int main(int argc, char **argv) 11 { 12 const char *pattern; 13 const char *errstr; 14 int erroffset; 15 pcre *expr; 16 char line[512]; 17 assert(argc == 2); /* XXX fixme */ 18 pattern = argv[1]; 19 if (!(expr = pcre_compile(pattern, 0, &errstr, &erroffset, 0))) { 20 fprintf(stderr, "%s: %s\n", pattern, errstr); 21 return EXIT_FAILURE; 22 } 23 while (fgets(line, sizeof line, stdin)) { 24 size_t len = strcspn(line, "\n"); 25 int matches[2]; 26 int offset = 0; 27 int flags = 0; 28 line[len] = '\0'; 29 while (0 < pcre_exec(expr, 0, line, len, offset, flags, matches, 2)) { 30 printf("%.*s%s%.*s%s", 31 matches[0] - offset, line + offset, 32 enter_reverse_mode, 33 matches[1] - matches[0], line + matches[0], 34 exit_reverse_mode); 35 offset = matches[1]; 36 flags |= PCRE_NOTBOL; 37 } 38 printf("%s\n", line + offset); 39 } 40 return EXIT_SUCCESS; 41 }Compilación:
pl@nereida:~/src/regexpr$ gcc -lpcre pcregrep.c -o pcregrep
Cuando se ejecuta espera un patrón en la línea de comandos y pasa a leer desde la entrada estandar. Las cadenas que casan se muestran resaltadas:
pl@nereida:~/src/regexpr$ ./pcregrep '\d+' 435 otro 23435 otro 23
hola hola
pl@nereida:~/src/python$ cat -n c2f.py 1 #!/usr/local/bin/python 2 import re 3 4 temp = raw_input( ' Introduzca una temperatura (i.e. 32F, 100C): ' ) 5 pattern = re.compile( "^([-+]?[0-9]+(\.[0-9]*)?)\s*([CF])$", re.IGNORECASE ) 6 mo = pattern.match( temp ) 7 8 if mo: 9 inputNum = float(mo.group( 1 )) 10 type = mo.group( 3 ) 11 celsius = 0.0 12 fahrenheit = 0.0 13 if ( type == "C" or type == "c" ) : 14 celsius = inputNum 15 fahrenheit = ( celsius * 9/5 ) + 32 16 else : 17 fahrenheit = inputNum 18 celsius = ( fahrenheit - 32 ) * 5/9 19 print " ", '%.2f'%(celsius), " C = ", '%.2f'%(fahrenheit), " F\n" 20 else : 21 print " Se experaba una temperatura, no se entiende", temp, "\n"
pl@nereida:~/src/ruby$ cat -n f2c_b 1 #!/usr/bin/ruby 2 3 # Primero leemos una temperatura 4 class Temperature_calculator 5 def initialize temp 6 comp = Regexp.new('^([-+]?\d+(\.\d*)?)\s*([CFcf])$') 7 if temp =~ comp 8 begin 9 cifra = Float($1) 10 @C,@F = ( $3 == "F" or $3 == "f")? [(cifra -32) * 5/9, cifra] : [cifra , cifra * 9/5 + 32] 11 end 12 else 13 raise("Entrada incorrecta") 14 end 15 end 16 17 def show 18 puts "Temperatura en Celsius: #{@C}, temperatura en Fahrenheit: #{@F}" 19 end 20 end 21 22 temperatura = Temperature_calculator.new(readline.chop) 23 temperatura.show
<SCRIPT LANGUAGE="JavaScript"><!-- function demoMatchClick() { var re = new RegExp(document.demoMatch.regex.value); if (document.demoMatch.subject.value.match(re)) { alert("Successful match"); } else { alert("No match"); } } function demoShowMatchClick() { var re = new RegExp(document.demoMatch.regex.value); var m = re.exec(document.demoMatch.subject.value); if (m == null) { alert("No match"); } else { var s = "Match at position " + m.index + ":\n"; for (i = 0; i < m.length; i++) { s = s + m[i] + "\n"; } alert(s); } } function demoReplaceClick() { var re = new RegExp(document.demoMatch.regex.value, "g"); document.demoMatch.result.value = document.demoMatch.subject.value.replace(re, document.demoMatch.replacement.value); } // --> </SCRIPT> <FORM ID="demoMatch" NAME="demoMatch" METHOD=POST ACTION="javascript:void(0)"> <P>Regexp: <INPUT TYPE=TEXT NAME="regex" VALUE="\bt[a-z]+\b" SIZE=50></P> <P>Subject string: <INPUT TYPE=TEXT NAME="subject" VALUE="This is a test of the JavaScript RegExp object" SIZE=50></P> <P><INPUT TYPE=SUBMIT VALUE="Test Match" ONCLICK="demoMatchClick()"> <INPUT TYPE=SUBMIT VALUE="Show Match" ONCLICK="demoShowMatchClick()"></P> <P>Replacement text: <INPUT TYPE=TEXT NAME="replacement" VALUE="replaced" SIZE=50></P> <P>Result: <INPUT TYPE=TEXT NAME="result" VALUE="click the button to see the result" SIZE=50></P> <P><INPUT TYPE=SUBMIT VALUE="Replace" ONCLICK="demoReplaceClick()"></P> </FORM>