English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
L'espressione regolare è solitamente chiamata “regex” o “RegExp”, ed è un modello utilizzato per abbinare combinazioni di caratteri all'interno di una stringa.
L'espressione regolare è uno degli strumenti più potenti disponibili oggi, in grado di gestire e manipolare efficacemente il testo.
Le espressioni regolari possono essere utilizzate per eseguire tutti i tipi diricerca di testoesostituzione di testooperazioni.
L'espressione regolare può essere un singolo carattere, può essere un modello più complesso.
In JavaScript, le espressioni regolari sono anche oggetti.
Puoi creare un'espressione regolare in due modi:
Usare l'espressione regolaretestocomposta da un modello incluso tra le barre oblique, come segue:
var regex = /w3codebox/g
o chiamare il metodo dell'oggetto RegExpCostruirefunzione, come segue:
var regex = new RegExp("w3codebox", "g");
Esempio di spiegazione:
w3codeboxè un modello (usato per la ricerca)
gè il modificatore (esegue la ricerca globale)
UtilizzaCostruirefunzione può fornire la compilazione in tempo reale dell'espressione regolare.
Quando non si conosce il modello e si riceve il modello da altre fonti (ad esempio, input utente), utilizzareCostruirefunzione.
Nota:QuestotestoLa sintassi utilizza il trattino obliquo (") per avvolgere il modello dell'espressione regolare, mentre la sintassi del costruttore utilizza virgolette (") per il modello.
In JavaScript, le tre stringhe più comuni usate per espressioni regolari sono:search(),replace()ematch().
search()Il metodo utilizza l'espressione per cercare corrispondenze e restituisce la posizione della corrispondenza.
replace()Il metodo restituisce una stringa modificata in cui viene sostituito il modello.
match()The method searches for matches with the regular expression in the string and then returns the matches as an Array object.
search()Il metodo esegue una ricerca per trovare corrispondenze tra l'espressione regolare e la stringa.
Se trova una corrispondenza, restituirà la posizione della prima corrispondenza, se non trova corrispondenze, restituirà-1:
var str = 'The question is to be, or not to be, that is to be.'; var pos = str.search('to be');Prova a vedere se ci sono <›>/<›>
Esempi seguenti dimostrano che coni
L'uso del modificatore dell'espressione regolare (ignora le maiuscole e le minuscole):
var str = 'The question is TO BE, or not to be, that is to be.'; var pos = str.search(/to be/i);Prova a vedere se ci sono <›>/<›>
L'espressione regolare può rendere la funzione di ricerca più potente (ad esempio, senza distinguere tra maiuscole e minuscole).
replace()Il metodo restituisce una nuova stringa che contiene parte o tutto il match del modello e sostituisce con l'elemento di sostituzione.
Il primo parametro è il valore da trovare, il secondo parametro è il valore da sostituire.
var str1 = 'The question is to be, or not to be, that is to be.'; var str2 = str1.replace('to be', 'ZZZ');Prova a vedere se ci sono <›>/<›>
By default,replace()The method only replaces the first match.
To replace all occurrences, use the one withg
Case-insensitive regular expression modifier (global search):
var str1 = 'The question is to be, or not to be, that is to be.'; var str2 = str1.replace(/to be/g, 'ZZZ');Prova a vedere se ci sono <›>/<›>
To replace case-insensitive code, use the one withi
Case-insensitive regular expression modifier:
var str1 = 'The question is TO BE, or not to be, that is to be.'; var str2 = str1.replace(/to be/gi, 'ZZZ');Prova a vedere se ci sono <›>/<›>
match()The method searches for matches with the regular expression in the string and then returns the matches as an Array object.
var str = 'POLLUTION: Air Pollution is the introduction of chemicals to the atmosphere'; var reg = str.match(/ion/g);Prova a vedere se ci sono <›>/<›>
Modifiers are used to perform global searches, case-sensitive, and multiline searches:
Modifier | Description | Esempio |
---|---|---|
g | Execute global matching, that is, find all matches, rather than stopping after the first match | Test it |
i | Execute case-insensitive matching | Test it |
m | Execute multiline matching | Test it |
Regular expression patterns include the use of letters, numbers, punctuation marks, etc., as well as a set of special regular expression characters.
Bracket []Used to find a series of characters:
Expression | Description | Esempio |
---|---|---|
[abc] | Find any character between brackets | Test it |
[0-9] | Find any character between brackets (any number) | Test it |
(x|y) | Find any specified replacement | Test it |
MetacharacterIt is a simple letter character, preceded by a backslash, which gives this combination a special meaning:
Metacharacter | Description | Esempio |
---|---|---|
\d | Find a digit | Test it |
\W | Find non-word characters | Test it |
\s | Find the space character | Test it |
QuantifierSpecify the position of the character sequence within brackets or the frequency:
Expression | Description | Esempio |
---|---|---|
z+ | Matching any string containing at least onez'sString | Test it |
z* | Matching any string containing zero or morez'sString | Test it |
z? | Matching any string containing zero or one occurrencez'sString | Test it |
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
test()Il metodo ricerca il modello nella stringa e restituisce true o false in base ai risultati.
exec()Il metodo ricerca il modello nella stringa e restituisce il testo trovato come oggetto.
test()Il metodo esegue una ricerca di corrispondenze nel testo specificato.
Se trova una corrispondenza, restituiscetrue; altrimenti, restituiscefalse.
Utilizzatest().
var str = "it.oldtoolbag.com"; var regex = new RegExp("h"); var ans = regex.test(str);Prova a vedere se ci sono <›>/<›>
Quando vuoi sapere se il modello desiderato è presente nella stringatest()Restituisce un valore booleano, diverso daexec()Restituisce una stringa.
exec()Il metodo esegue una ricerca di corrispondenze nel testo specificato.
Se trova una corrispondenza, questo metodo restituisce il testo corrispondente; altrimenti, restituisce null.
var str = "it.oldtoolbag.com"; var regex = new RegExp("h"); var ans = regex.exec(str);Prova a vedere se ci sono <›>/<›>
Calcola il numero di vocali nella stringa:
Inserisci del testo in un campo di input per visualizzare il numero di lettere vocali:
Numero di lettere vocali inserite:
Per una guida completa delle proprietà e dei metodi, visita il nostroRiferimento RegExp JavaScript.
La parte di riferimento contiene descrizioni e esempi di tutte le proprietà e metodi di RegExp.