neo4j-contrib / neo4j-apoc-procedures

Awesome Procedures On Cypher for Neo4j - codenamed "apoc"                     If you like it, please ★ above ⇧            
https://neo4j.com/labs/apoc
Apache License 2.0
1.72k stars 493 forks source link

When apoc.text.replace extracts several values, bind them directly to variables. #1828

Closed mojo2go closed 3 years ago

mojo2go commented 3 years ago

When I use apoc.text.replace, I often wish to extract several values at once and immediately assign each to its own variable. I normally set up an assignment per variable like this:

UNWIND ["John Smith - Consultant", 
        "Willy Brown - Teacher", 
        "Jen Mack - Radiologist"] AS person

WITH apoc.text.replace(person, '(\w+)\s(\w+)\s-\s(\w)', '$1,$2,$3') AS extract
WITH split(extract,',')[0] AS first,
     split(extract,',')[1] AS last,
     split(extract,',')[2] AS role
RETURN first, last, role

...and that works fine, but I wish I could make that less verbose. It would be great if I could do something like load the results directly into a map of named parameters like this:

UNWIND ["John Smith - Consultant", 
        "Willy Brown - Teacher", 
        "Jen Mack - Radiologist"] AS person

WITH apoc.text.replace(person, '(\w+)\s(\w+)\s-\s(\w)', {first:$1, last:$2, role:$3}) AS p
RETURN p.first, p.last, p.role

And...while we're at it, there is in javascript what is called the 'rest parameter'...which I think is named to describe the 'rest of' the incoming parameters. It's three dots placed at the end of a parameter list. It servers as a catch-all for all remaining incoming parameter values. That can be useful here too. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

conker84 commented 3 years ago

@mojo2go did you tried with apoc.text.regexGroups?

https://neo4j.com/labs/apoc/4.1/overview/apoc.text/apoc.text.regexGroups/

I think it does the job

conker84 commented 3 years ago

@mojo2go ping!

conker84 commented 3 years ago

closed for lack of feedback