을 얻을 Regex 식기 조건

0

질문

내가 원하는 출력하고 다음에 기반한 정규 표현식이다. 고 싶어 어떤 종류의 재사용성에 따라 파일 포맷

파일 포맷

   export const datas = [
      {
        id: 1,
        name: "CODE_SLOT",
        codePosition: 0,
        codeType: "_",
        slotPosition: 1,
        slotType: "_",
      },
      {
        id: 2,
        name: "CODE-SLOT",
        codePosition: 0,
        codeType: "-",
        slotPosition: 1,
        slotType: "-",
      },
    ];

코드에 대한 제품 코드

export const getProductCode = (code, codePosition, codeType) => {
  return (
    code.replace(/\.[^/.]+$/, "").split(codeType)[codePosition] ||
    code.replace(/\.[^/.]+$/, "").split(codeType)[0] ||
    ""
  );
};



const images = [{
    name: "toys-blue_wide.jpg"
}]

const selectedFileNameFormat = datas[0]

const output = images.map((image) => ({
  productCode: getProductCode(
    image?.name,
    selectedFileNameFormat?.codePosition,
    selectedFileNameFormat?.codeType
  ),
}));

console.log(output)

예상 출력의 제품 코드

productCode: toys-blue

코드 슬롯

export const getSlot = (slot, slotPosition, slotPosition) => {
  return (
    slot.replace(/\.[^/.]+$/, "").split(slotPosition)[slotPosition] ||
    slot.replace(/\.[^/.]+$/, "").split(slotPosition)[0] ||
    ""
  );
};
    const images = [{
    name: "toys-blue_wide.jpg"
}]
const selectedFileNameFormat = datas[0]

const output = images.map((image) => ({
  slotCode: getSlot(
    image?.name,
    selectedFileNameFormat?.codePosition,
    selectedFileNameFormat?.codeType
  ),
}));

예상 출력을 위한 슬롯

slotCode: wide
ecmascript-6 javascript regex
2021-11-23 03:41:23
1

최고의 응답

1

이해하고 있다면 당신의 질문에 정확하게 당신이 원하는 분석/추출물 문자열에서,즉"toy-blue_wide.jpg"일 productCode 모든 "_" 문자,즉 "toy-blue"slotCode모든 "_" 제외한 파일 확장자가 있습니다. 당신이 사용할 수 있는 하나의 정규 표현식을 캡처 이러한 두 가지 부분으로 그들의 각각의 그룹입니다.

/^(.*)_(.*)\./

첫 번째 괄호 캡처 및 제품 코드 두 번째 캡처 슬롯 코드입니다. 사용 RexExp.프로토 타입입니다.exec 검색할 수 있습을 통해 각각의 파일 이름 및 추출물 배열의 일치합니다.

const [, productCode, slotCode] = /^(.*)_(.*)\./.exec(name);

또한 통지를 사용하는 경우 배열 선언 및 할당을 우리는 우리를 건너뛰는 첫 번째 요소입니다. 이 때문에 첫 번째 요소에서 돌아 .exec 는 전체 문자열에 일치하는 반면,지수 1..n 캡처 한 그룹이 있습니다.

const images = [{
  name: "toys-blue_wide.jpg"
}];

const codeAndSlotRegex = /^(.*)_(.*)\./;

images.forEach(({ name }) => {
  const [, productCode, slotCode] = /^(.*)_(.*)\./.exec(name);
  console.log({ productCode, slotCode });
});

업데이트

을 허용하는 동적으로 선택하면 파일 이름을 파서 내가 지정한 특정 REGEX 정규에 대한 각 당신이 원하는 형식을 분석합니다.

const fileNameFormats = [
  {
    id: 1,
    name: "Code-Slot",
    matcher: /^(.*)-(.*)\./
  },
  {
    id: 2,
    name: "Code_Slot",
    matcher: /^(.*)_(.*)\./
  }
];

반복 배열의 이미지와 사용하여 특별히 선택한 정규. 제공하는 대체 배열의 값을 경우에 일치하는 것이 실패하고 기본 코드 슬롯 값입니다.

const output = images.map((image) => {
  const [, productCode = "", contentSlot = ""] = selectedFileNameFormat.matcher.exec(
    image?.name
  ) ?? [];
  return {
    productCode,
    contentSlot
  };
});

Edit get-regex-expression-before-a-condition

2021-11-23 07:35:59

@요셉은 나도 몰라,다른 게시지 않는 정말 아무것도 설명하고 모든 codesandbox 가 선택한 두 가지 옵션 중에서 로그인 현지 상태가 됩니다. 나는 확실하지 않다 당신이 원하는 무슨을에서 이해한다.
Drew Reese

@요셉 확인,하지만 나는 무엇인지 묻는 옵션을 의미합니다. 는 경우 사용자"를 선택하는 코드 슬롯",무엇을 예정이 다음에 일어날,무엇을 선택하는 옵션을 의미합니까? 에 대해 동일한 경우 사용자"를 선택하는 Code_Slot"? 이라고 생각했고 싶은 파일을 선택하는 이름 형식을 분석합니다. 그것은 말 그대로는 것과 같은 간단한 분할에 상징이""코드고"슬롯"?
Drew Reese

@요셉이 나는 지금이다. 나는데 대답을 여기에는 다음?
Drew Reese

Drew Reese

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................