2012-03-12 8 views
6

Ho una stringa lunga che devo analizzare in una matrice di stringhe che non superino i 50 caratteri di lunghezza. La parte delicata di questo per me è assicurarsi che la regex trovi l'ultimo spazio bianco prima di 50 caratteri per fare una pausa netta tra le stringhe poiché non voglio che le parole vengano tagliate.Suddividere il testo dopo una lunghezza specificata ma non rompere le parole usando i grails

public List<String> splitInfoText(String msg) { 
    int MAX_WIDTH = 50; 
    def line = [] String[] words; 
    msg = msg.trim(); 
    words = msg.split(" "); 
    StringBuffer s = new StringBuffer(); 
    words.each { 
     word -> s.append(word + " "); 
     if (s.length() > MAX_WIDTH) { 
      s.replace(s.length() - word.length()-1, s.length(), " "); 
      line << s.toString().trim(); 
      s = new StringBuffer(word + " "); 
     } 
    } 
    if (s.length() > 0) 
     line << s.toString().trim(); 
    return line; 
} 
+0

fornire il proprio input e output atteso? – anubhava

+0

elenco pubblico splitInfoText (String msg) { \t \t int MAX_WIDTH = 50; \t \t \t \t linea def = [] \t \t \t \t String [] parole; \t \t \t msg = msg.trim(); \t \t \t \t words = msg.split (""); \t \t \t \t StringBuffer s = new StringBuffer(); \t \t \t \t words.each {parola -> \t \t \t \t \t s.append (parola + " "); \t \t \t \t \t \t se (s.length()> MAX_WIDTH) { \t \t \t \t \t \t \t s.replace (s.length() - word.length() - 1, s.length (), ""); . \t \t \t \t \t \t \t \t linea << s.toString() trim() \t \t \t \t \t \t \t \t s = new StringBuffer (word + " "); \t \t \t \t \t \t \t} \t \t \t \t \t} \t \t \t \t se (s.length()> 0) \t \t \t \t \t linea << s.toString().trim() \t \t \t \t \t linea di ritorno; \t \t \t} – Nimmy

+0

@Nimmy: ho tentato di inserire il codice nel corpo principale della domanda, ma sembrerà molto meglio se modifichi la tua domanda e inserisci il codice. – PearsonArtPhoto

risposta

5

Prova questo:

List<String> matchList = new ArrayList<String>(); 
Pattern regex = Pattern.compile(".{1,50}(?:\\s|$)", Pattern.DOTALL); 
Matcher regexMatcher = regex.matcher(subjectString); 
while (regexMatcher.find()) { 
    matchList.add(regexMatcher.group()); 
} 
+0

Questo non ha funzionato per me quando l'ho provato. – JRSofty

+0

@JRSofty: avevo dimenticato di inizializzare il parametro 'matchList' - funziona ora? E se così non fosse, qual è esattamente il problema? –

+0

Ora funziona. L'originale ha catturato gli spazi bianchi ma non il testo tranne una parola. Funziona come me lo aspetterei. – JRSofty

4

credo che una versione groovier di risposta di Tim è:

List matchList = (subjectString =~ /(?s)(.{1,50})(?:\s|$)/).collect { it[ 1 ] } 
+0

Non conosco affatto Groovy, ma questo mi sembra molto divertente. +1 :) –

Problemi correlati