สตริง - regex สำหรับจับเฉพาะตัวอักษรและตัวเลข ขีดกลาง ขีดล่าง และจุด โดยไม่มีเครื่องหมายวรรคตอนซ้ำ
ฉันเป็นมือใหม่กับ regex และ typescript และกำลังพยายามที่จะให้ regex ตรงกับ:
1. must start with alphanumeric (repeating is fine)
2. can contain alphanumeric (repeating is fine)
3. can contain periods, underscores, and/or hyphens (no repeating)
4. must end with alphanumeric (repeating is fine)
ฉันได้ทำการค้นหา และพบตัวอย่างหลายตัวที่ค่อนข้างคล้ายกัน และฉันพยายามปรับแต่งให้มันทำงานตามที่ฉันต้องการ แต่ฉันยังไม่สามารถหาวิธีแก้ไขที่ถูกต้องได้ หากใครมี regex ที่ดีที่จะช่วยและคำอธิบายว่าทำไม จะทำให้ฉันเรียนรู้ระบบได้มากขึ้น นั่นจะยอดเยี่ยมมาก
นี่คือตัวอย่างบางส่วนของสิ่งที่ฉันพยายามตรวจสอบว่าเป็นสตริงที่ยอมรับได้:
this.is.Valid
also_a_valid_1
Me-too.im_an-ugly.but_vALid-5tring
และตัวอย่างบางส่วนของสตริงที่ไม่ถูกต้องซึ่ง regex ปัจจุบันของฉันอนุญาต แต่ควรล้มเหลวเนื่องจากมีจุด/ขีดกลาง/ขีดล่างซ้ำกัน และมีจุด ขีดกลาง ขีดล่างอยู่ที่จุดเริ่มต้นและสิ้นสุด:
-this..should..not.be.valid....
..THIS__.-also-should..fail-
why..IS_regex--so.confusing-for-n0obs
และนี่คือตัวอย่างของ regex ที่ฉันกำลังใช้:
validateString(myString: string): boolean {
return (/^[a-zA-Z0-9_\-\.]+((\.-?|-\.?)[a-zA-Z0-9_\-\.]+)*$/.test(varKey))
}
คำตอบ #1
ใช้ :
^[a-z0-9]+(?:[._-][a-z0-9]+)*$
คำอธิบาย:
^ # beginning of line
[a-z0-9]+ # 1 or more alphanum
(?: # start non capture group
[._-] # period, underscore or hyphen
[a-z0-9]+ # 1 or more alphanum
)* # end group, may appear 0 or more times
$
เดโม
var test = [
'this.is.Valid',
'also_a_valid_1',
'Me-too.im_an-ugly.but_vALid-5tring',
'-this..should..not.be.valid....',
'..THIS__.-also-should..fail-',
'why..IS_regex--so.confusing-for-n0obs',
'h',
'sTrInG',
];
console.log(test.map(function (a) {
return a+' :'+/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/i.test(a);
}));