2016-06-07 59 views
1

我有一個字段,用戶可以在其中搜索某些內容。他們應該能夠搜索^[0-9a-zA-Z*]$正則表達式If-Then-Else條件

但是不可能只搜索字符*(通配符)。必須至少有一個其他的字母或數字。 a* or *a or 1* or *1有效。

所以必須至少有一個數字/字母不相等*有效搜索。

我認爲它應該可以通過if/then/else條件來實現。這是我的嘗試!

"^(?(?=[*])([0-9a-zA-Z:\]{1,})|([0-9a-zA-Z:\*]*))$" 
if character = * 
then [0-9a-zA-Z:\]{1,} = user has to enter at least one (or more) characters of the group 
else = [0-9a-zA-Z:\*]* = user has to enter 0 or more characters of the group 

但它不工作...

+0

試** [這](https://regex101.com/r/rF4wZ8/1)**如果向前看符號在你的正則表達式 – rock321987

+0

支撐或['^ [0-圖9a-ZA-Z *] * [0-9A-ZA-Z] [0-9A-ZA-Z *] * $'](https://regex101.com/r/eW7wD6/1)。 –

+0

java正則表達式引擎 – Hammelkeule

回答

1

您可以使用

^[0-9a-zA-Z*]*[0-9a-zA-Z][0-9a-zA-Z*]*$ 

regex demo

此正則表達式匹配零個或多個字母/數字/星號,然後是強制性字母或數字,然後是零個或多個字母/數字/星號。

或者,你可以要求一個字符串至少有1個字母或數字:

^(?=.*[0-9a-zA-Z])[0-9a-zA-Z*]+$ 

another demo^(?=.*[0-9a-zA-Z])積極的超前將需要一個字母或一個數字後零或更多的任何字符,但換行符。它也可以寫成^(?=.*\p{Alnum})[\p{Alnum}*]+$(在Java中使用雙轉義反斜槓)。

Java demo

String rx = "(?=.*\\p{Alnum})[\\p{Alnum}*]+"; 
System.out.println("****".matches(rx));  // FALSE 
System.out.println("*a**".matches(rx));  // TRUE