이것은 이전에 묻는 질문을 기반으로 한 새로운 질문 입니다. 구분 기호를 기반으로 문자열에서 부분 문자열 추출 (답변 허용)
나는 끈이있다 ]d1[)½}06~9N110375286414~1T12345ABCD~D150600~S12345ABCDEF98765}
참고 : }
위의 예에서 뒤에 공백이 있습니다.
위의 문자열에서 내 구분 기호는 9N, 1T, D, S이며 구분 기호 뒤에있는 부분 문자열을 추출 ~
하거나 EOL이 될 때까지 추출해야합니다 .
그 아래에있는 바이올린이 기대에 D1
와 S1
대신 구분 기호로 D
와 S
각각.
나는 2 개의 문제에 직면하고있다
1) 단일 문자 구분 기호 문제 ( D
, S
)
2) }
값을 반환 할 때 문자열 끝을 어떻게 제거해야합니까 ? 예를 들어 구분 기호 S
가 있는 하위 문자열 12345ABCDEF98765
은12345ABCDEF98765}
Fiddle (결과는 콘솔 기반)
JS
// Use ]d1[)½}06~9N110375286414~1T12345ABCD~D150600~S12345ABCDEF98765}
// Note: There is an empty space after the } char as shown above
var dataNames = {
'9N': 'PPN',
'1T': 'batchNumber',
'D': 'expireDate',
'S': 'serialNumber'
};
var input = document.querySelector("input");
document.querySelector("button").addEventListener("click", function() {
var str = input.value;
console.log(parseGS1(str));
});
function parseGS1(str) {
var fnc1 = "~";
var data = {};
//remove ]d1[)½}06~
str = str.slice(10);
while (str.length) {
//get the AI identifier: 1T, 9N etc
let aiIdent = str.slice(0, 2);
//get the name we want to use for the data object
let dataName = dataNames[aiIdent];
//update the string
str = str.slice(2);
switch (aiIdent) {
case "1T":
case "9N":
let fnc1Index = str.indexOf(fnc1);
//eol or fnc1 cases
if (fnc1Index == -1) {
data[dataName] = str.slice(0);
str = "";
} else {
data[dataName] = str.slice(0, fnc1Index);
str = str.slice(fnc1Index + 1);
}
break;
case "D":
case "S":
//eol or fnc1 cases
break;
default:
console.log("unexpected ident encountered:", aiIdent);
return false;
break;
}
}
return data;
}
정규식을 사용하여이 작업을 수행 할 수도 있습니다. 이 솔루션을 사용하면 문자열의 일부가 움직여도 작동합니다.
function getData(input) {
input = input.slice(0, input.length - 2);
// The regex has two capture groups.
// Group 1 gets the identifier, this can also be the start of the string.
// Group 2 gets all the characters between the identifier and the '~' char or '} '.
// The third group is a non-capturing group, it is used to find the delimiter where the next part starts.
var
regex = /(^|9N|1T|D|S)(.*?)(?:~|$)/g,
data = {},
match = regex.exec(input);
while (match !== null) {
switch(match[1]) {
case '9N':
data.PPN = match[2];
break;
case '1T':
data.batch = match[2];
break;
case 'D':
data.expireDate = match[2];
break;
case 'S':
data.serial = match[2];
break;
}
var msg = 'Found ' + match[0] + ' / identifier = ' + match[1] + ' / value = ' + match[2] + '. ';
console.log(msg);
// Get the next match.
match = regex.exec(input);
}
return data;
}
var input = ']d1[)½}06~9N110375286414~1T12345ABCD~D150600~S12345ABCDEF98765} ',
input2 = ']d1[)½}06~9N110375286414~D150600~1T12345ABCD~S12345ABCDEF98765} ';
console.log(getData(input));
console.log(getData(input2));
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다