4 回答

TA貢獻1805條經驗 獲得超9個贊
你可以使用
String regex = "#[^.#]*[^.#\\s][^#.]*\\.\\w+";
細節
#
- 一個#
符號[^.#]*
.
- 除and之外的零個或多個字符#
[^.#\\s]
- 任何字符,但.
,#
和空格[^#.]*
.
- - 除and之外的零個或多個字符#
\.
- 一個點\w+
- 1+ 個單詞字符(字母、數字或_
)。
String s = "# #.id\nendpoint/?userId=#someuser.id\nHi #someuser.name, how are you?";
String regex = "#[^.#]*[^.#\\s][^#.]*\\.\\w+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group(0));
}
輸出:
#someuser.id
#someuser.name

TA貢獻1155條經驗 獲得超0個贊
重新定義的要求是:
找花樣
#A.B
A
可以是任何東西,除了空格,也不能包含#
或.
B
只能是常規的 ASCII 字母或數字
將這些要求轉換為(可能的)正則表達式:
#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+
解釋:
#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+ # The entire capture for the Java-Matcher:
# # A literal '#' character
[^.#]+ # Followed by 1 or more characters which are NOT '.' nor '#'
( \\.) # Followed by a '.' character
(?<! ) # Which is NOT preceded by (negative lookbehind):
# # A literal '#'
\\s+ # With 1 or more whitespaces
[A-Za-z0-9]+ # Followed by 1 or more alphanumeric characters
# (PS: \\w+ could be used here if '_' is allowed as well)
測試代碼:
String input = "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id #.id %^*#@*(.H(@EH Ok, # some spaces here .but none here #$p€??@l.$p€??@l that should do it..";
System.out.println("Input: \""+ input + '"');
System.out.println("Outputs: ");
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+")
.matcher(input);
while(matcher.find())
System.out.println('"'+matcher.group()+'"');
在線嘗試。
哪些輸出:
Input: "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id #.id %^*#@*(.H(@EH Ok, # some spaces here .but none here #$p€??@l.$p€??@l that should do it.."
Outputs:
"#someuser.id"
"#someuser.name"
"#@*(.H"
"# some spaces here .but"

TA貢獻1719條經驗 獲得超6個贊
您可以嘗試以下正則表達式:
#(\w+)\.(\w+)
筆記:
如果您不想捕獲任何組,請刪除括號。
在你的java正則表達式字符串中你需要轉義每一個
\
這給
#(\\w+)\\.(\\w+)
如果
id
僅由數字組成,則可以通過以下方式更改第二\w
個[0-9]
如果
username
包含除字母表、數字和下劃線以外的其他字符,則必須更改\w
為具有明確定義的所有授權字符的字符類。
代碼示例:
String input = "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id, #.id.";
Matcher m = Pattern.compile("#(\\w+)\\.(\\w+)").matcher(input);
while (m.find()) {
System.out.println(m.group());
}
輸出:
#someuser.id
#someuser.name

TA貢獻1789條經驗 獲得超10個贊
#(\w+)[.](\w+)
結果兩組,例如
endpoint/?userId=#someuser.id -> group[0]=someuser and group[1]=id
添加回答
舉報