2013-06-02 6 views
6

Posso trasformare stringa #ff00fffirstword#445533secondword#008877thirdword atrasformo '# ff00fffirstword # 445533secondword # 008877thirdword' in formato tag HTML

<font color='#ff00ff'>firstword</font><font color='#445533'>secondword</font><font color='#008877'>thirdword</font> 

Utilizzando regexp in javascript o ActionScript3 programma?

Ho provato il codice qui sotto, ma non è perfetto (codice ActionScript3):

var pat:RegExp = /(#\w{6})([^#]+)/g; 
var html:String = t.replace(pat, "<font color=\'$1\'>$2</font>"); 
trace(html); // output :<font color='#ff00ff'>firstword</font><font color='#445533'>secondword</font><font color='#008877'>thirdword</font> 

Se c'è un altro # in quella stringa, l'uscita sarebbe non essere come voglio che sia. Non so come scrivere una regexp più forte per raggiungere questo obiettivo.

+0

Per inciso, 'tag font' è deprecato e non è garantito il funzionamento in futuro. È preferibile utilizzare CSS, ad es. ' ...' –

risposta

5

Prova ad utilizzare un (|) Operatore or e un lookahead per il fine linea:

var pat:RegExp = /(#[0-9a-f]{6})([^#]+?)(?=#|$)/gi; 
var html:String = t.replace(pat, "<font color=\'$1\'>$2</font>"); 
trace(html); 

Vorrei anche personalmente uso [0-9a-f] invece di \w qui per ogni evenienza. Il lookahead (?=#|$) assicura che sia la fine della linea o un altro hash. Ho anche inserito il flag i anche nel caso.

Dal momento che si hanno anche hash randagi, è possibile utilizzare questo:

var pat:RegExp = /(#[0-9a-f]{6})(.+?)(?=#[0-9a-f]{6}|$)/gi; 
var html:String = t.replace(pat, "<font color=\'$1\'>$2</font>"); 
trace(html); 

vedere l'output here.

E il debuggex:

Regular expression image

+1

se la stringa di origine è '#ff00fffirstword # 445533secondword ## 008877thi # rdword #' l'output dovrebbe essere firstword< font color = '# 445533'> secondword # thi # rdword #

+0

@RexSmith Aggiunta una regex nuova per occuparsene! Non sapevo che hai anche degli hash vaganti, quindi dovrebbe funzionare ora :) – Jerry

+0

haha, funziona! grazie a tutti! –

6

Descrizione

Si potrebbe usare questa espressione regolare

Regex: ([#][0-9a-f]{6})(.*?)(?=[#]|$) Sostituire con <font color='\1'>\2</font>

enter image description here

Javascript Esempio di codice:

<script type="text/javascript"> 
    var re = /([#][0-9a-f]{6})(.*?)(?=[#]|$)/; 
    var sourcestring = "#ff00fffirstword#445533secondword#008877thirdword"; 
    var replacementpattern = "<font color='\1'>\2</font>"; 
    var result = sourcestring.replace(re, replacementpattern); 
    alert("result = " + result); 
</script> 

$sourcestring after replacement: 
<font color='#ff00ff'>firstword</font><font color='#445533'>secondword</font><font color='#008877'>thirdword</font> 
+0

Come hai generato il diagramma di flusso regex? – DhruvPathak

+0

Non dovresti 'sourcestring' essere' # ff00fffirstword # 445533secondword # 008877thirdword'? –

+0

@ Jordan Trudgett & Rex Smith: Sì, già corretto, si prega di aggiornare il browser. –