Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
Regex for parsing functions and their optional arguments in parenthesis

I'm very close to having this regex work the way I want it to. My regex is:

const text = 'func0 func-1(1)    func-2(1, 2) func3';
const matches = text.matchAll(\s*([^(]*)(?:\(([^\)]+)\))?)

I need this to parse out to multiple groups where group 1 is the function name (ex func0) and group 2 is the arguments if they exist. Arguments and parenths are not required.

This example should give me the matches:

Match 0: 'func0'
Group 0: 'func0'
Group 1: ''

Match 0: 'func1'
Group 0: 'func1'
Group 1: '1'

Match 0: 'func2'
Group 0: 'func2'
Group 1: '1, 2'

Match 0: 'func3'
Group 0: 'func3'
Group 1: ''

My regexp currently only works if there all functions have params and/or if a argumentless function is last and it can be the only one.

My issue really is just with how to optionally allow the arguments for any function anywhere in the string. I need to check if a space is found before a parenthesis and if so end the match group.

Here is an example regex: https://regexr.com/6jiv2

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I slightly modified your regex to this: \s*(?<fname>[^ (]+)(?:\((?<args>[^\)]+)\))?

Test here:

  • https://regex101.com/r/IFSxJl/1
  • https://regexr.com/6jj6f

With this you can use named groups, to access the function name and the arguments separately.

The following are Match, group1(fname) and group2(args):

Match 0: 'func0'
fname: 'func0'
args: ''

Match 0: 'func1'
fname: 'func1'
args: '1'

Match 0: 'func2'
fname: 'func2'
args: '1, 2'

Match 0: 'func3'
fname: 'func3'
args: ''
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think this gives what you're looking for. The only material difference is that "Group 1" for a function without arguments returns null instead of ''.

const text = "func0 func-1(1)    func-2(1, 2) func3";
const matches = [...text.matchAll(/([^ \(]+)(?:\(([^\)]+)\))?/g)];
console.log(JSON.stringify(matches));

// [["func0","func0",null],["func-1(1)","func-1","1"],["func-2(1, 2)","func-2","1, 2"],["func3","func3",null]]
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda