Java is a language of choice for millions of developers worldwide. Java è un linguaggio di scelta per milioni di sviluppatori in tutto il mondo. In a series of articles I will show simple tips and techniques which make Java extremely powerful and yet simple to use. In una serie di articoli mi mostrerà semplici suggerimenti e tecniche che rendono Java estremamente potente, eppure semplice da usare. Today’s article is about using regex, a pattern matcher incorporated in Java (from 1.4 I believe). L'articolo di oggi è di circa usando regex, un pattern matcher incorporati in Java (da 1,4 credo).

Here is a sample code (line in bold) to count the number of words in any amount of text. Qui c'è un esempio di codice (linea in grassetto) per contare il numero di parole in qualsiasi quantità di testo. The sample program counts the number of words in the argument to the program. Il programma di esempio conta il numero di parole in argomento per il programma. The argument must be quoted to ensure separate words are clubbed together in a single sentence by the operating system. L'argomento deve essere indicato al fine di garantire separare le parole sono clubbed insieme in una sola frase dal sistema operativo.

 public class WordCount {   public static void main(String args[]) { System.out.println(java.util.regex.Pattern.compile(”[\\w]+”).split(args[0].trim()).length); } } classe pubblica Wordcount (public static void main (String args []) (System.out.println (java.util.regex.Pattern.compile ( "[\ \ w ]+"). split (args [0]. trim ( )). lunghezza);)) 

Sample usage: Esempi di utilizzo:
java WordCount “This is a sample phrase with 8 words” java Wordcount "Questo è un esempio di frase con 8 parole"

All its does is compile the regular expression “\w” which matches with words and splits the phrase in an array of individual words. Tutti i suoi non è compilare l'espressione regolare "\ w", che corrisponde con le parole e con la frase divide in una serie di singole parole. Then the total length of the array is printed. Quindi la lunghezza totale delle serie è stampato.