简体   繁体   中英

My regular expression is not working Node.js?

I have a regular expression which extracts some text to an array. The code works fine in the frontEnd but it doesn't work in the node.js server.

Whenever I run the code in the backend I get this error message:

TypeError: Cannot read property '1' of null
   at C:\Users\PureTech\master\app\server\routes.js:26:11
   at Layer.handle [as handle_request] (C:\Users\PureTech\node_modules\express\lib\router\layer.js:95:5)
   at next (C:\Users\PureTech\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (C:\Users\PureTech\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (C:\Users\PureTech\node_modules\express\lib\router\layer.js:95:5)
   at C:\Users\PureTech\node_modules\express\lib\router\index.js:277:22
   at Function.process_params (C:\Users\PureTech\node_modules\express\lib\router\index.js:330:12)
   at next (C:\Users\PureTech\node_modules\express\lib\router\index.js:271:10)
   at C:\Users\PureTech\node_modules\express-session\index.js:433:7
   at C:\Users\PureTech\node_modules\connect-mongo\lib\connect-mongo.js:305:11 

This is the code I'm talking about. It is a regular expression that extracts specific numbers in the "text" variable to an array.

var text = '[Extracted] id: 194805284, Waxaad $55 ka heshay  MAXAMED  CABDILAAHI JAAMAC SAALAX (252906152669) Tar: 15/04/19 08:44:40, Haraagaagu waa $1,042.7[Extracted] id: 193537533, Waxaad $3 ka heshay  ABDULKADIR  ABDIDAHIR FARAH (907794804) Tar: 14/04/19 10:15:32, Haraagaagu waa $59.17';
var reso = text.replace("$", "");
var textArray = reso.split('[Extracted]');

var regularExpression = new RegExp(/id:\s+([0-9]+).+Waxaad\s+([0-9]+).+[^\(]+\(([0-9]+)\)\s+Tar:\s+([0-9\/\s:]+)/i);
var output = [];
var item;
for(var i = 1; i < textArray.length;  i++){
    item = textArray[i].match(regularExpression);
    output.push({
        id: item[1].trim(),
        amount: item[2].trim(),
        time: item[3].trim(),
        number: item[4].trim()
    });
}

console.log(output);

I want this script to work on the backend(node.js) as it works on the frontEnd.

You have to define:

var regularExpression = new RegExp("id:\s+([0-9]+).+Waxaad\s+([0-9]+).+[^\(]+\(([0-9]+)\)\s+Tar:\s+([0-9\/\s:]+)", "i");

Or

var regularExpression = /id:\s+([0-9]+).+Waxaad\s+([0-9]+).+[^\(]+\(([0-9]+)\)\s+Tar:\s+([0-9\/\s:]+)/i;

I figured out the problem.

  1. I removed all the '$' signs by using this script var reso = text.split('$').join("");
  2. I removed the new RegExp.

And then it worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM