3 回答
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用的一個(gè)可能的正則表達(dá)式是:
^((\d+\.)*\d+) \D*$
捕獲組 1 將在哪里舉行您的比賽。
解釋:
^ # Start of the String
( # Open capture group 1:
(\d+\.) # One or more digits, followed by a dot
* # Repeated 0 or more times
\d+ # Followed by 1 or more digits
) # Closing capture group 1
# Followed by a space
\D* # Followed by 0 or more non-digits
$ # Followed by the end of the String
和^將使$我們查看整個(gè)字符串。這\D*將確??崭窈蟮淖幼址袥](méi)有任何數(shù)字。并且確保始終有一個(gè)前導(dǎo)數(shù)字,在它之前有一個(gè)或多個(gè)\d+(其中是非負(fù)數(shù))。(\d+\.)*#.#
要提取此值,您可以將此正則表達(dá)式與 a 一起使用String.matches,.replaceFirst如下所示:
// TODO: Give proper method name
String test(String str){
String regex = "^((\\d+\\.)*\\d+) \\D*$";
if(str.matches(regex))
return str.replaceFirst(regex, "$1");
// The `$1` will leave just the match of the first capture group,
// removing everything else we don't need
else
return null;
}
如果后面沒(méi)有任何空格的單個(gè)數(shù)字(即"123")也應(yīng)該匹配,則可以通過(guò)更改為對(duì)正則表達(dá)式進(jìn)行細(xì)微修改\\D*$,( \\D*)?$以便空格變?yōu)榭蛇x。
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
Using(\d+\.)+\d不會(huì)匹配第一個(gè)條目,因?yàn)槭褂昧吭~+它必須至少匹配一個(gè)數(shù)字和一個(gè)點(diǎn)。
您可能會(huì)做的是使用錨^來(lái)斷言字符串的開(kāi)頭并使用模式來(lái)匹配數(shù)字,然后重復(fù)匹配點(diǎn)和數(shù)字零次或多次,這樣您也可以匹配第一個(gè)條目。
匹配后,確保數(shù)字后面沒(méi)有非空白字符。如果后面不能有更多數(shù)字,您可以使用額外的負(fù)前瞻。
^\d+(?:\.\d+)*(?!\S)(?!.*\d)
在 Java 中:
String regex = "^\\d+(?:\\.\\d+)*(?!\\S)(?!.*\\d)";
解釋
^字符串的開(kāi)始\d+(?:\.\d+)*匹配 1+ 位數(shù)字,后跟重復(fù)模式以匹配點(diǎn)和 1+ 位數(shù)字(?!\S)負(fù)前瞻檢查左邊的內(nèi)容不是非空白字符(?!.*\d)負(fù)前瞻檢查右邊的內(nèi)容不包含數(shù)字
TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
我們可以嘗試對(duì)每一行使用以下正則表達(dá)式模式:
^(?!\D*\d[^0-9.]+\d).*\b\d+(?:\.\d+)?(?=\\s|$).*$
解釋:
^ from the start of the line
(?!\D*\d[^0-9.]+\d) assert that two (or more) separate numbers
do not occur in the line
.* then consume anything, up to
\b\d+(?:\.\d+)? an integer, or complete decimal
(?=\\s|$) where either a space or the end of the line follows
.* then consume anything, up to
$ the end of the line
這是使用此模式的 Java 代碼:
String line = "45.67.21234.3";
String pattern = "^(?!\\D*\\d[^0-9.]+\\d).*\\b\\d+(?:\\.\\d+)?(?=\\s|$).*$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("match");
}
else {
System.out.println("no match");
}
我已經(jīng)根據(jù)您的所有輸入對(duì)其進(jìn)行了測(cè)試,它似乎正在工作。
添加回答
舉報(bào)
