รูปแบบ Regex สำหรับอักขระ Pilcrow (¶) หรือ Partial Differential (∂)

Aug 19 2020

ฉันต้องการค้นหา / แทนที่หรือแปลงอักขระที่แตกต่างกันของพิลโครว์ / บางส่วนในสตริงตามที่แสดงเป็น

สิ่งที่ฉันคิดว่าจะได้ผล แต่ไม่ได้ผล:

const value = 'Javascript Regex pattern for Pilcrow (¶) or Partial Differential (∂) character';
const matches = value.match(/\u2029/gmi);
console.log(matches);

แต่กลับว่างเปล่า

พูดตามตรงฉันไม่แน่ใจด้วยซ้ำว่าจะบรรลุสิ่งที่ต้องทำอย่างไร

คำตอบ

5 ÁlvaroGonzález Aug 19 2020 at 21:16

ที่ถูกต้อง Unicode จุดรหัสเป็นU + 00B6และU + 2202ไม่U + 2029 คุณจะต้องใช้ช่วงอักขระ []ในนิพจน์ของคุณ:

const value = 'Javascript Regex pattern for Pilcrow (¶) or Partial Differential (∂) character';
const matches = value.match(/[\u00B6\u2202]/gmi);
console.log(matches);

แน่นอนว่าคุณไม่จำเป็นต้องหนีตั้งแต่แรก:

const value = 'Javascript Regex pattern for Pilcrow (¶) or Partial Differential (∂) character';
const matches = value.match(/[¶∂]/gmi);
console.log(matches);

สุดท้าย แต่ไม่ท้ายสุดคุณพูดว่า:

ปัจจุบันแสดงเป็น

หากเป็นเช่นนั้นเป็นไปได้มากว่าจะเริ่มต้นด้วยการเข้ารหัสไม่ถูกต้อง กล่าวอีกนัยหนึ่งคุณจะไม่พบหรือเพราะไม่มี ฉันขอแนะนำให้คุณจัดการเรื่องนี้ก่อน

3 KunalMukherjee Aug 19 2020 at 20:34

ใช้String.prototype.codePointAtเพื่อแยกจุดรหัสยูนิโคด UTF-16 และแปลงเป็นเลขฐานสิบหก

const toUnicodeCodePointHex = (str) => {
    const codePoint = str.codePointAt(0).toString(16);
    return '\\u' + '0000'.substring(0, 4 - codePoint.length) + codePoint;
};

const value = 'Javascript Regex pattern for Pilcrow (¶) or Partial Differential (∂) character';

const re = new RegExp(['¶', '∂'].map((item) => toUnicodeCodePointHex(item)).join('|'), 'ig');

const matches = value.match(re);
console.log(matches);

ดูสิ่งนี้ดีมากarticleโดย Mathias Bynens

1 JordanStubblefield Aug 19 2020 at 20:55

คุณสามารถค้นหาได้ด้วยค่าฐานสิบหกหรือฐานแปด:

const matches = value.match(/\u00B6|\u2202/g);

Regex สำหรับแต่ละ:

Pilcrow: \u00B6หรือ\xB6หรือ\266

ความแตกต่างบางส่วน: \u2202