Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
Regex coincide con identificadores de variables, identificadores de funciones, parámetros de funciones y nombres de clases de una cadena

Hay, necesito tu ayuda...
Así que tenemos un código de ejemplo en textarea y usaremos expresiones regulares para hacer coincidir todo:

  • nombre de la clase
  • identificador de función y variable, y
  • parámetro entre paréntesis (...)

este es el retorno esperado:

(abc) (a) (abc123) (taHandler) (elem) (patrón) (caret_start) (ClassMates) (nombre) (edad) (displayInfo)

si desea editar en regex101 : https://regex101.com/r/UCI6Np/1

Ya hago la mitad del trabajo hasta que me quedo atascado en la coincidencia de identificadores de variables separados por coma. Realmente aprecio cualquier ayuda de ustedes. si algo no está claro, no dude en preguntarme en la sección de comentarios.

 const str = document.getElementById('val_').value; const regex = /(?<=(let|var|const|function|class)\s+)(\w+)/g; let m; while ((m = regex.exec(str)) !== null) { // avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { if( groupIndex === 2 ){ console.log(`match:(${match})`); } }); }
 /* we need to match : - class name - function and variable identifier - parameter inside parentheses (...) this is the expected return : (abc) (a) (abc123) (taHandler) (elem) (pattern) (caret_start) (ClassMates) (name) (age) (displayInfo) */ /* edit on regex101: https://regex101.com/r/UCI6Np/1 */
 <textarea id="val_" style="width:100%;height:200px;"> this just example code for regex matching purpose: var abc = 123; let a = 'ok'; const abc123 = 'yep'; function taHandler(elem) { let pattern = /\r?\n|\r/, caret_start = elem.selectionStart, caret_end = elem.selectionEnd, elmval_ = elem.value; class ClassMates{ constructor(name,age){ this.name=name; this.age=age; } displayInfo(){ return this.name + "is " + this.age + " years old!"; } } </textarea>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Casi lo tenías hecho. Una dificultad que encontré es, como dijiste, hacer coincidir los identificadores de variables separados por comas.

Creo que si comprueba que están precedidos por una coma y seguidos de = (+ espacios en blanco opcionales), estará bastante seguro:

 (?<=(let|var|const|function|class)\s+)(\w+)|(?<=,\s+)(\w+)(?=\s*=)|(?<=[\(,])(\w+)(?=[\),])|(?<=}\s+)(\w+)(?=\()

Para reconocer funciones en una clase compruebo si están precedidas por } y seguidas por ( (+ espacios en blanco opcionales). De esta manera excluimos el constructor.

about 4 years ago · Juan Pablo Isaza Report

0

He usado esta expresión para leer el código fuente de cpp. esta es una expresión que usé para encontrar el nombre de la función.

 "(?<returnType>(\w+(\[\])|\w+\*|\w+))([\n\r\s])(?<methodName>\w+)\s*\((\s*((?:\s*(?<parameterType>(\w+(\[\])|\w+\*|\w+))\s+(?<parameter>\w+)\s*,?\s*))?)+\)"

Que puede detectar el nombre de la función como:

  • int principal()
  • int principal (int a, int b)
  • int principal(int[] a)
  • int principal(int* ptr,int a)
  • int* principal()
  • vacío principal()
  • int[] principal()

Y también capaz de obtener esos nombres en el parámetro.

 public void evaluate() { foreach (string data in strData.Split('\n')) { MatchCollection matchs = Regex.Matches(data, @"(?<returnType>(\w+(\[\])|\w+\*|\w+))([\n\r\s])(?<methodName>\w+)\s*\((\s*((?:\s*(?<parameterType>(\w+(\[\])|\w+\*|\w+))\s+(?<parameter>\w+)\s*,?\s*))?)+\)"); foreach (Match match in matchs) { string returnType = match.Groups["returnType"].Captures[0].Value; string methodName = match.Groups["methodName"].Captures[0].Value; var typeParameterPair = new List<KeyValuePair<string, string>>(); int i = 0; foreach (var capture in match.Groups["parameterType"].Captures) { typeParameterPair.Add(new KeyValuePair<string,string>(match.Groups["parameterType"].Captures[i].Value, match.Groups["parameter"].Captures[i].Value)); i++; } FunctionData tempData = new FunctionData(); tempData.returnType = returnType; tempData.methodName = methodName; tempData.parameters = typeParameterPair; funcData.Add(tempData); } } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!