Javascript:搜索子字符串模式并返回找到的字符串

时间:2018-11-28 09:58:53

标签: javascript

我有一个由几个字段组成的字符串。其中两个长度总是会变化的。如果所有字段的长度都固定,我可以简单地使用子字符串。

示例:

  

48001MCAbastillas2200800046300017100518110555130000123

字段划分如下:

  

480 | 01 | MCAbastillas | 2200800046300017 | 100518 | 110555 | 130000 | 123

加粗的字段是长度不同的字段。它们分别代表名称和金额。我已经发布了这个问题,但是我错误地用Java对其进行了标记。我试图将提供的答案解释为Javascript,但由于它不是专家,所以整日没有产生任何结果:(

4 个答案:

答案 0 :(得分:4)

您可以使用正则表达式捕获组

const regex = /^(.{3})(.{2})(\D+)(.{16})(.{6})(.{6})(\d+)(.{3})$/
const str = '48001MCAbastillas2200800046300017100518110555130000123'
const values = str.match(regex)
console.log(values)

答案 1 :(得分:2)

var input = '48001MCAbastillas2200800046300017100518110555130000123';
// match parts with regex
var match = input.match(/^(.{3})(.{2})([a-zA-Z]+)(.{16})(.{6})(.{6})(\d+)(.{3})$/);
// remove first element (full matching input)
match.shift();
// build output
var output = match.join(' | ');
console.log(output);

答案 2 :(得分:0)

const test = [
  '48001MCAbastillas2200800046300017100518110555130000123',
  '48001MCAbasti2200800046300017100518110555130000123',
  '48001MCAbastillasXYZ2200800046300017100518110555130000123',
  '48001MCAbastillas2200800046300017100518110555130000999123',
  '48001MCAbastillas2200800046300017100518110555130123',
  '48001MCAbastillasXYZ2200800046300017100518110555130000999123',
  '48001MCAbasti220080004630001710051811055513123'
]

const p = /(?<name>\D+)(\d{28})(?<amount>\d+)(\d{3}$)/

console.log (test.map (s => s.match (p).groups))

答案 3 :(得分:0)

一个更复杂的版本,它根据已知值分解所有部分。正则表达式的答案就是解决之道。

var r1 = "48001MCAbastillas2200800046300017100518110555130000123";
var r2 = "48001RANDOM220080004630001710051811055512345123";

function extract(str) {
    var i = 5,max = str.length;
    var parts = [], cut1, cut2 = (max - 3);
    for(;i<max;i++) {
        if (! isNaN(parseInt(str[i]))) {
            cut1 = i;
            break;
        }
    }
    parts.push(str.substr(0,3));
    parts.push(str.substr(3,2));
    parts.push(str.substr(5,(cut1 - 5)));
    parts.push(str.substr(cut1,16));
    parts.push(str.substr((cut1 + 16),6));
    parts.push(str.substr((cut1 + 16 + 6),6));
    parts.push(str.substr((cut1 + 16 + 12),(cut2 - (cut1 + 16 + 12))));
    parts.push(str.substr(cut2,3));      
    return parts;
}

console.log(extract(r1));
console.log(extract(r2));