1

What's the best way in nodeJS to parse to following string to extract values described below?

client 111.222.333.44#59699: query: jadssdffsdnisa.website.com IN A -ED (81.11.11.175)

Current code:

//parsing
var c_ip = data.split("client ")[1].split("#")[0] 
var sdomain  = data.split("query:")[1].split(".")[0]  

console.log("c_ip: " + c_ip + '\n');    
console.log("sdomain: " + sdomain + '\n');  

Results in:

c_ip: 130.225.244.66

sdomain:  paul
2
  • What assumptions can be made towards the length of c_ip and the structure of the query? Commented Jul 5, 2016 at 8:10
  • The c_ip will be always a IPv4. Commented Jul 5, 2016 at 8:11

2 Answers 2

2

This very depends on how your input string arrives but assuming that it has always that same format you could do something like this

var task = "client 111.222.333.44#59699: query: jadssdffsdnisa.website.com IN A -ED (81.11.11.175)"

var c_ip = task.split("client ")[1].split("#")[0]
var sdomain  = task.split("query: ")[1].split(".")[0] 

console.log("c_ip:", c_ip)
console.log("sdomain:", sdomain)

further, if it varies more you could use regex. @jens-habegger has a good example

Sign up to request clarification or add additional context in comments.

3 Comments

It won't varietes that much. Using your code there seems to be some whitespaces before the subdomain aren't they? I've edited first post.
This is probably faster than my answer using regex.
@peke_peke indeed. query: needed an additional space at the end. it works now. The space that still remains is based on the console.log() function
0

Use basic regex:

var string = "client 111.222.333.44#59699: query: jadssdffsdnisa.website.com IN A -ED (81.11.11.175)"

var c_ip_reg = /client\s(.*)#/;
var c_ip = string.match(c_ip_reg);

var sdomain_ref = /query:\s(.*?)\/;
var sdomain = string.match(sdomain_ref);

I'm aware this can be shortened into a multi-group match, but for the sake of readability I tried to be as verbose as possible.

.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.