[英]Regular expression to match inverse of special characters
我是RegExp的新手,我嘗試在Flex AS3中創建一個RegExp,該RegExp匹配表達式my_regex
給定模式中未提供的任何內容。 也就是說,我想匹配除“ ^():,?+ * /”之外的所有內容。 (不含雙引號)。 但是我的程序表現得很奇怪,它在鍵入替代字符時顯示錯誤字符串。 請提出我的正則表達式有什么問題。
`
<fx:Script>
<![CDATA[
private const my_regex:RegExp = /\b[^():,?+*\.]/g;
private function validateNow(evt:Event):void {
if (my_regex.test(ti.text)) {
ti.errorString = null;
} else {
ti.errorString = "some error here";
}
}
]]>
</fx:Script>
<mx:TextInput id="ti" change="validateNow(event)"/>
`
您的if
邏輯似乎被顛倒了。
擺脫\\b
因為它表示“單詞邊界”(此處不需要)。
字符類開始處的^
(方括號內的內容)將其取反。 字符類任何其他位置的^
表示該文字字符(這就是為什么我在末尾添加一個字符)的原因。
如果您使用var ti:TextInput = evt.target as TextInput;
在您的方法中,您將能夠將該方法應用於多個不同的TextInputs(以及為什么要使用舊的mx
組件,最好使用spark
)。
這是我的解決方案(第二個TextInput為紅色,因為正則表達式不允許使用空格):
這里的代碼:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
private const my_regex:RegExp = /[^():,?+*\.^]/;
private function handleChange(evt:Event):void {
var ti:TextInput = evt.target as TextInput;
trace("text=" + ti.text);
trace("test=" + my_regex.test(ti.text) + "\n");
if (my_regex.test(ti.text)) {
ti.errorString = 'Only these chars are allowed: ():,?+*.^';
} else {
ti.errorString = null;
}
}
]]>
</fx:Script>
<s:TextInput id="ti1" change="handleChange(event)"
horizontalCenter="0" top="50"/>
<s:TextInput id="ti2" change="handleChange(event)"
horizontalCenter="0" top="100"/>
<s:TextInput id="ti3" change="handleChange(event)"
horizontalCenter="0" top="150"/>
</s:Application>
正則表達式的一些問題...
首先,您需要轉義許多這些字符,因為它們在正則表達式中具有特殊含義。 您可以通過在每個字符前面加反斜杠來轉義其特殊功能(從而僅引用字符)。 老實說,您可以逃避所有這些。
編輯:\\ b在大多數情況下確實標記了一個單詞邊界,但是,這與我們這里的目的無關。
您修改后的正則表達式是...
private const my_regex:RegExp = /[\^\(\)\:\,\?\+\*\\\.]/g;
另一個注意事項是,如果運行my_regex.test(ti.text)
,則如果這些字符中的任何一個出現在字符串中,它將返回true。 為了使錯誤字符串在匹配時有一個值,您必須反轉邏輯。 在調用.test
之前,我使用過not( !
)運算符。
private function validateNow(evt:Event):void {
if (!my_regex.test(ti.text)) {
ti.errorString = null;
} else {
ti.errorString = "some error here";
}
}
我強烈建議您方便使用正則表達式參考。 我個人最喜歡的是ActionScript 3.0 Bible 2e 。 第12章詳盡介紹。 如果您喜歡Web資源, 則AS3文檔可以很好地工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.