Rob
Rob

Reputation: 11788

How to make regex in node.js return the first matching group?

I have a string from a text file from which I have to extract a value. Here's the line containing the value (there are many other lines):

<CONFIG_entry name="Konfiguration:Allgemeine Einstellungen:CMS-Server:Port" valuetext="15000" value="15000" adr="CL1.2.1" unit="" />

What I want to get out is the valuetext value:

15000

I fiddled around with an online Regex tester and ended up with this expression, which gave me exactly the value I was looking for (15000):

/CMS-Server:Port"\s+valuetext="(.*)"\s+value/

Next, I wanted to use this line in node.js like this:

var myFile = fs.readFileSync('myfile.txt','utf8');
var pattern = new RegExp(/CMS-Server:Port"\s+valuetext="(.*)"\s+value/);
var matches = myFile.match(pattern);
console.log("Result: " + matches[0]);

The problem: matches[0] gives me this

CMS-Server:Port" valuetext="15000" value

instead of

15000

What am I doing wrong?

Upvotes: 1

Views: 1176

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You did not specify g modifier, that is why match returns the full match with match[0], and the value of the first capturing group with match[1].

If you specify g, then you will have an array of all matches, but no access to captured texts and you would have to use exec.

Also, you have a problem with the regex: .* may match much more than you need. Use [^"]* or \d* (since the field only contains digits) instead.

Besides, you can safely remove new RegExp(...), just use var pattern = /.../.

So, I suggest

/CMS-Server:Port"\s+valuetext="(\d*)"\s+value/
....
console.log("Result: " + matches[1]);

Or use XML Parser:

var myXML = '<CONFIG_entry name="Konfiguration:Allgemeine Einstellungen:CMS-Server:Port" valuetext="15000" value="15000" adr="CL1.2.1" unit="" />';
var parseXml;

if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

var xml = parseXml(myXML);
alert(xml.documentElement.getAttribute("valuetext"));

Upvotes: 2

Related Questions