Quiero hacer coincidir una combinación de y/o expresión y hacer coincidir solo oraciones intermedias, por ejemplo
test1 test2 and test2 or test4 test5Quiero obtener coincidencias test1 test2, test2, test4 test5
Probé esta expresión regular https://regex101.com/r/FFLtg6/1 pero no funciona:
(.+)(((and|or)\s+)?)+Actualización: necesito una expresión regular porque es parte de una expresión regular más grande.
Esto es lo que estás buscando:
const txt = "lorem ipsum and dolor and sit or amet consecteturand elit"; console.log(txt.split(/ and | or /)); const text = "test1 test2 and test2 or test4 test5"; const regexp = /(?<=^|and |or ).*?(?= and| or|$)/g; console.log(text.match(regexp));PD Pero tenga en cuenta que la función de búsqueda positiva no es compatible con todos los navegadores
const text = " test1 test2 and test2 or test4 test5 "; const regexp = /\s*(?!and|or)\b.*?(?=and|or|$)/g; console.log(text.match(regexp)); const text = " test1 test2 and test2 or test4 test5 "; const regexp = /(?!and|or|\s)\b.*?(?=\s*(and|or|$))/g; console.log(text.match(regexp));Probablemente haría lo obvio:
const rxWords = /\S+/g; const rxConnectors = /^(and|or)$/i; const nonConnector = w => ! rxConnectors.test(w) ; function getInterestingWords( s ) { const corpus = s ?? '' ; const matches = corpus.match( rxWords ) ; const words = matches.filter( nonConnector ) ; return words; }Dado que, ejecutar
const text = 'test1 test2 and test2 or test4 test5f' ; const interestingWords = getInterestingWords(text); establece palabras interestingWords en el valor esperado
[ 'test1', 'test2', 'test2', 'test4', 'test5' ]