Problema
Trova le posizioni di tutte le occorrenze di un modello all'interno di una stringa. (Grazie @DonMcCormack )
Soluzione
Utilizzare le funzioni di corrispondenza del modello
source = "this is a racecar and ere noon stressed desserts for Stanley Yelnats saw Anna was there";
palindrome = (Pat Regex( "[a-zA-Z][a-zA-Z ]{0,999}" )) >> firstpart + // one or more first letters
(Pat Regex( "[a-zA-Z ]{0,1}" )) + // optional middle letter
Expr( Reverse( firstpart ) ); // the tail
list = {}; // places to
positions = {}; // keep results
Pat Match(
source,
Pat Repeat( // repeat *is* a loop, within the source string
(Pat Pos() >> location + // capture current position in string
palindrome >> another + // capture the text of the palindrome match
Pat Test( // this function runs some JSL to see if the current position matches
Insert Into( list, another );// the JSL saves
Insert Into( positions, location );// two answers
1 // pattest returns 1(OK) because we are not actually testing anything...just wanted to run some JSL
)//
)
| // above adds to list, below skips forward a letter to try again
Pat Len( 1 ) // this bit is more important than it looks; it matches all the text that isn't interesting
)
);
Show( list, positions );
list = {"una macchina da corsa a", "ere", "mezzogiorno", "dessert accentati", "Stanley Yelnats", "ha visto Anna era", "ere"};
posizioni = {8, 22, 26, 31, 53, 69, 84};
Discussione
PatRepeat è una funzione di corrispondenza del modello che ripete il suo modello finché può. Non può saltare il testo indesiderato senza l'alternativa PatLen (1) che consente di ignorare un carattere alla volta fino a trovare un'altra istanza del modello desiderato.
Puoi anche usare un modello molto semplice:
source = "this is a racecar and ere noon stressed desserts for Stanley Yelnats saw Anna was there";
reallysimple = "is";
list = {}; // places to
positions = {}; // keep results
Pat Match(
source,
Pat Repeat( // repeat *is* a loop, within the source string
(Pat Pos() >> location + // capture current position in string
reallysimple >> another + // capture the text of the match
Pat Test( // this function runs some JSL to see if the current position matches
Insert Into( list, another );// the JSL saves
Insert Into( positions, location );// two answers
1 // pattest returns 1(OK) because we are not actually testing anything...just wanted to run some JSL
)//
)
| // above adds to list, below skips forward a letter to try again
Pat Len( 1 ) // this bit is more important than it looks; it matches all the text that isn't interesting
)
);
Show( list, positions );
list = {"is", "is"};
posizioni = {2, 5};