提取两个特殊字符之间的字符串部分-Javascript

时间:2018-11-08 06:09:53

标签: javascript ecmascript-6

我有一个复杂的字符串,作为响应的一部分。 但是我需要提取特殊字符之间的字符串部分,即 开始特殊字符->,结束特殊字符<-。 这些标记之间需要显示的任何内容都应该被忽略

要更改的字符串

"validation error [claimDto:Reporter.HomeNumber->Value entered must be a valid phone number<-, claimDto:Lobs.PostalCode->Please enter a valid ZIP code.<-, claimDto:Lobs.HomeNumber->Value entered must be a valid phone number]"

期望值:

Value entered must be a valid phone number
Please enter a valid ZIP code.

2 个答案:

答案 0 :(得分:1)

一个简单的match可以做到,向后->,向后<-,并使用全局标志:

const input = "validation error [claimDto:Reporter.HomeNumber->Value entered must be a valid phone number<-, claimDto:Lobs.PostalCode->Please enter a valid ZIP code.<-, claimDto:Lobs.HomeNumber->Value entered must be a valid phone number]";
console.log(input.match(/(?<=->).*?(?=<-)/g));

某些浏览器尚不支持lookbehind-不使用lookbehind, match 而不是使用backbehind的开始箭头,遍历每个匹配项并提取组:

const input = "validation error [claimDto:Reporter.HomeNumber->Value entered must be a valid phone number<-, claimDto:Lobs.PostalCode->Please enter a valid ZIP code.<-, claimDto:Lobs.HomeNumber->Value entered must be a valid phone number]";
let match;
const re = /->(.*?)(?=<-)/g;
const output = [];
while (match = re.exec(input)) {
  output.push(match[1]);
}
console.log(output);

答案 1 :(得分:0)

您可以在不需要后援的情况下接近@CertainPerformance的答案:

const input = "validation error [claimDto:Reporter.HomeNumber->Value entered must be a valid phone number<-, claimDto:Lobs.PostalCode->Please enter a valid ZIP code.<-, claimDto:Lobs.HomeNumber->Value entered must be a valid phone number]";

const matchText = /->(.+)/;
input.split('<-')
    .map(s => matchText.exec(s))
    .filter(x => x)
    .map(x => x[1]);

结果:

[
    "Value entered must be a valid phone number",
    "Please enter a valid ZIP code.",
    "Value entered must be a valid phone number]"
]

您的输入字符串是否缺少最后一个<-?这就是导致尾随]字符;)

的原因

说明:

input.split('<-')   // split the string into segments that end with '<-' (removes the '<-' characters too)

.map(s => /->(.+)/.exec(s))    // capture any text after '->' to the end of the string. Any strings without '->' in them will not match and will return null

.filter(x => x) // filter out any null regexp results    

.map(x => x[1]); // put out the captured text from each regexp result (x[0] is the entire match, x[1] is just the captured text)