使用值修改特定文本

时间:2015-08-18 06:01:47

标签: javascript regex

我用readFile方法读取了一个文本文档,我得到了当前的字符串。 我需要修改里面的一些特定字段并保存文件并保留原始格式

在读取文件中我得到以下"字符串"

\r\nAPP_HOST=mo-d6fa.corp\r\nAPP_PORT=5000\r\nINS_PORT=50100\r\nPORT=66000\r\n

我需要更改属性的数字

  1. PORT = 4000
  2. APP_PORT = 4000
  3. 我使用fs.readFile(filePath, 'utf8'),响应就是这个文件

3 个答案:

答案 0 :(得分:1)

您可以将其修改为对象,设置值,然后使用Array.prototype.reduce返回字符串:

var rawValues = "\r\nAPP_HOST=mo-d6fa.corp\r\nAPP_PORT=5000\r\nINS_PORT=50100\r\nPORT=66000\r\n";

// #1 You need to turn raw string into an array using String.prototype.split
// #2 It's time to reduce the array into an object to be able to access
// config values as a key-value pair store
var values = rawValues.trim().split("\r\n").reduce(
  function(result, next, index, sourceArray) {
    var keyValuePair = sourceArray[index].split("=");
    result[keyValuePair[0]] = keyValuePair[1];

    return result;
  }, {});


// Now you can alter config values like a dictionary:
values["PORT"] = "9995";
values["APP_PORT"] = "9999";
// or using dot syntax if possible settings have valid JavaScript
// variable names...
values.PORT = "9995";
values.APP_PORT = "9999";
// ...more settings...

// #3 Once you've edited your settings, it's time to reduce each property
// as part of a new raw string containing all configurations.
rawValues = Object.keys(values).reduce(function(previousValue, property, index) {
  previousValue += property + "=" + values[property] + "\r\n";

  return previousValue;
}, "");


// Now PORT and APP_PORT contain their new values...
document.getElementById("rawResult").textContent = JSON.stringify(rawValues);
<div id="rawResult"></div>

建议

恕我直言,如果您可以将配置转换为有效的JSON生活,那就更容易了。

例如,您的原始配置可以是{ "APP_HOST": "mo-d6fa.corp", "APP_PORT": 5000, "INS_PORT": 50100, "PORT": 66000 }。了解这是如何简化您的问题的:

var rawConfig = '{ "APP_HOST": "mo-d6fa.corp", "APP_PORT": 5000, "INS_PORT": 50100, "PORT": 66000 }';
var config = JSON.parse(rawConfig);
config["APP_PORT"] = 6000;
config["PORT"] = 7000;
rawConfig = JSON.stringify(config);

document.getElementById("result").textContent = rawConfig;
<div id="result"></div>

您可以使用JSON这是一个众所周知的模式而不是滚动您自己的配置解析器,它有一个内置的,开箱即用的解析器作为地球上每个Web浏览器的一部分,NodeJS甚至非.NET平台,如.NET,Java ......

答案 1 :(得分:1)

这两者的正则表达式非常相似。这是一个刺:

var portRegex = /\nPORT=\d+/g;
var appPortRegex = /\nAPP_PORT=\d+/g;

var fileStr = fs.readFile(filePath, 'utf8');
fileStr = fileStr
    .replace(portRegex, '\nPORT=' + 4000)
    .replace(appPortRegex, '\nAPP_PORT=' + 4000);

答案 2 :(得分:1)

找到确切PORT条目的问题可以通过仅在行的开头与/m修饰符(在多行模式下)匹配来强制^匹配来解决在一行的开头:

/^(PORT\s*=\s*)\d+/m
/^(APP_PORT\s*=\s*)\d+/m

&#13;
&#13;
var re = /^(APP_PORT\s*=\s*)\d+/m; 
var re2 = /^(PORT\s*=\s*)\d+/m; 
var str = 'APP_HOST=mo-d6fa.corp\nAPP_PORT=5000\nINS_PORT=50100\nPORT=66000';
var result = str.replace(re, '$1NEWVALUE').replace(re2, '$1ANOTHERVALUE');
document.write(result);
&#13;
&#13;
&#13;