我正在嘗試使用以下規則創建正則運算式字串
- 用戶名介于 4 到 25 個字符之間。
- 它必須以字母開頭。
- 它只能包含字母、數字和下劃線字符。
- 它不能以下劃線字符結尾。
當它滿足這個標準時,我希望輸出為真,否則為假,但我的測驗用例只得到假,這是我的代碼
public class Profile {
public static String username(String str) {
String regularExpression = "^[a-zA-Z][a-zA-Z0-9_](?<=@)\\w \\b(?!\\_){4,25}$";
if (str.matches(regularExpression)) {
str = "true";
}
else if (!str.matches(regularExpression)) {
str = "false";
}
return str;
}
主班
Profile profile = new profile();
Scanner s = new Scanner(System.in);
System.out.print(profile.username(s.nextLine()));
輸入
"aa_"
"u__hello_world123"
輸出
false
false
固定:感謝所有貢獻的人
uj5u.com熱心網友回復:
您可以使用
^[a-zA-Z][a-zA-Z0-9_]{3,24}$(?<!_)
^[a-zA-Z]\w{3,24}$(?<!_)
^[a-zA-Z][a-zA-Z0-9_]{2,23}[a-zA-Z0-9]$
^\p{Alpha}[a-zA-Z0-9_]{2,23}\p{Alnum}$
請參閱正則運算式演示。
詳情:
^- 字串的開始[a-zA-Z]- 一個 ASCII 字母[a-zA-Z0-9_]{3,24}/\w{3,24}- 三到二十四個 ASCII 字母、數字或下劃線$- 字串結束(?<!_)- 一個否定的lookbehind,確保沒有_(在字串的末尾)。
請注意,{3,24}使用它并不是{4,25}因為第一個[a-zA-Z]模式已經匹配單個字符。
用法:
public static String username(String str) {
return Boolean.toString( str.trim().matches("[a-zA-Z]\\w{3,24}$(?<!_)") );
// return Boolean.toString( str.trim().matches("\\p{Alpha}[a-zA-Z0-9_]{2,23}\\p{Alnum}") );
// return Boolean.toString( str.trim().matches("[a-zA-Z][a-zA-Z0-9_]{2,23}[a-zA-Z0-9]") );
}
請參閱Java 演示:
import java.util.*;
import java.util.regex.*;
class Ideone
{
public static String username(String str) {
return Boolean.toString( str.trim().matches("[a-zA-Z]\\w{3,24}$(?<!_)") );
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(username("u__hello_world123")); // => true
System.out.println(username("aa_")); // => false
}
}
uj5u.com熱心網友回復:
聽起來像\p{L}開頭的任何字母,中間和結尾的\w 單詞字符。\p{Alnum}
^\p{L}\w{2,23}\p{Alnum}$
在 regex101 上查看這個演示- 感謝 @Thefourthbird 在 ideone.com 上提供Java 演示
我不確定是否需要啟用UNICODE_CHARACTER_CLASS或(?U)支持\wunicode。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525928.html
標籤:爪哇正则表达式细绳循环
