我看了一下其他計算器問題,並不能找到一個問同樣的問題的最後一個字符,所以這裏是:僅匹配第一和一個字符串
你如何匹配第一個和一個字符串的最後一個字符(可以是多行或空的)。
因此,例如:
String = "this is a simple sentence"
注意該字符串包括開始和結束引號。
如何獲得字符串開始,用引號(「)結束匹配第一個和最後一個字符
我想:
^"|$" and \A"\Z"
,但這些並沒有產生預期的結果。
感謝您的幫助提前:)
我看了一下其他計算器問題,並不能找到一個問同樣的問題的最後一個字符,所以這裏是:僅匹配第一和一個字符串
你如何匹配第一個和一個字符串的最後一個字符(可以是多行或空的)。
因此,例如:
String = "this is a simple sentence"
注意該字符串包括開始和結束引號。
如何獲得字符串開始,用引號(「)結束匹配第一個和最後一個字符
我想:
^"|$" and \A"\Z"
,但這些並沒有產生預期的結果。
感謝您的幫助提前:)
這是你在找什麼?如果它開始與結束"
String input = "\"this is a simple sentence\"";
String result = input.replaceFirst("(?s)^\"(.*)\"$", " $1 ");
這將空格替換輸入字符串的第一個和最後一個字符。由於DOTALL
標誌由(?s)
指定,它也將在多行中工作。
爲什麼不使用基於charAt
獲得第一和最後一個字符的簡單邏輯方法的字符串?對空的/不完整的字符串進行一些檢查,你應該完成。
你的方式可行,但如果我想用空格替換引號(「」),效率並不是最高的。這就是爲什麼我想用String.replaceAll(regexPattern,「」);' – Sinker
它怎麼樣*效率不高? 'String#replaceAll'幾乎總是比簡單的字符替換方法調用更加昂貴。另外,如果你想讓字符串不帶引號,你總是可以根據'substring'調用返回一個視圖。 –
我該怎麼做? if(string.charAt(0).equals(「\」「)and string.charAt(string.length() - 1).equals(」\「」))newString = String.subString(1,string.length () - 2);' – Sinker
匹配整個輸入".*"
的正則表達式。在java中,它看起來像這樣:
String regex = "\".*\"";
System.out.println("\"this is a simple sentence\"".matches(regex)); // true
System.out.println("this is a simple sentence".matches(regex)); // false
System.out.println("this is a simple sentence\"".matches(regex)); // false
如果你想刪除引號,使用此:
String input = "\"this is a simple sentence\"";
input = input.replaceAll("(^\"|\"$)", "")); // this is a simple sentence (without any quotes)
如果你想這多條線路上工作,使用:
String input = "\"this is a simple sentence\"\n\"and another sentence\"";
System.out.println(input + "\n");
input = input.replaceAll("(?m)(^\"|\"$)", "");
System.out.println(input);
產生輸出:
"this is a simple sentence"
"and another sentence"
this is a simple sentence
and another sentence
說明正則表達式(?m)(^"|"$)
的:
(?m)
「行的開始然後一個「之後和換行符的正則表達式的剩餘部分之前插入符和美元匹配」(^"|"$)
裝置^"
OR "$
,這意味着裝置雙引號「或」雙引號,然後行尾「String regexp = "(?s)\".*\"";
String data = "\"This is some\n\ndata\"";
Matcher m = Pattern.compile(regexp).matcher(data);
if (m.find()) {
System.out.println("Match starts at " + m.start() + " and ends at " + m.end());
}
你有沒有嘗試這個辦法:'「*‘'(爲正則表達式),應該是這樣的,如果你進入它作爲字符串'’\」 * \‘’' – Kaj
這真不明白你的意思。 。匹配*第一個和最後一個字符是什麼?你已經給出了一個示例輸入,但沒有解釋爲什麼你的正則表達式應該或不應該匹配它。 –
@Kaj'。*'不允許換行字符,所以這對我來說是一個問題。 @Jon Skeet,當他們都是引號時,我想要得到第一個和最後一個字符的匹配。如果這是有道理的。 – Sinker