[英]Regex error in Typescript not matching dot
我正在使用此正則表達式來驗證僅允許一個點和數字的輸入字段。 它與javascript完美兼容。 但是,將其與打字稿一起使用時,它僅接受數字,並且在匹配時為dot(。)提供null。
這是我的正則表達式對象:
RegExp = new RegExp(/^[0-9]*\.?[0-9]*$/g)
這就是我使用它的方式。
@HostListener('keydown', [ '$event' ])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
let current: string = this.changeRate.nativeElement.value;
let next: string = current.concat(event.key);
console.log(next+" : "+String(next).match(this.regex)+" : " +event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
此語法是錯誤的: RegExp = new RegExp(/^[0-9]*\\.?[0-9]*$/g)
你要么寫
this.regex = /^[0-9]*\\.?[0-9]*$/g
要么
this.regex = new RegExp("^[0-9]*\\\\.?[0-9]*$", "g")
(在字符串中使用\\\\.
正確輸出\\.
) 我假設打字稿在幕后做了一些事情,試圖以第二種方式對其進行解析,並且它正在轉義.
而不是直接寫\\.
這里的TypeScript沒有什么特別的(畢竟TypeScript只是帶有類型注釋的JavaScript)。 引用MDN: RegEx
有兩種創建RegExp對象的方法: 文字符號和構造函數 。 為了指示字符串,文字符號的參數不使用引號,而構造函數的參數則使用引號。
以下三個表達式創建相同的正則表達式:
/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');
和:
使用構造函數時,需要正常的字符串轉義規則(當包含在字符串中時,在特殊字符前加\\)。 例如,以下等同:
var re = /\w+/;
var re = new RegExp('\\w+');
但是,您的實際問題是,看起來您使用了Regex類名作為變量名。 否則,您的正則表達式定義就可以了。
var regex = new RegExp(/^[0-9]*\\.?[0-9]*$/g); const str = `1.1`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.