[英]Java and regular expression, substring
使用正則表達式時,我完全迷失了。 我得到生成的字符串,如:
Your number is (123,456,789)
如何過濾出123,456,789
?
您可以使用此正則表達式提取包括逗號在內的數字
\(([\d,]*)\)
捕獲的第一個組將有您的比賽。 代碼將如下所示
String subjectString = "Your number is (123,456,789)";
Pattern regex = Pattern.compile("\\(([\\d,]*)\\)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
String resultString = regexMatcher.group(1);
System.out.println(resultString);
}
正則表達式的說明
"\\(" + // Match the character “(” literally
"(" + // Match the regular expression below and capture its match into backreference number 1
"[\\d,]" + // Match a single character present in the list below
// A single digit 0..9
// The character “,”
"*" + // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
")" +
"\\)" // Match the character “)” literally
String str="Your number is (123,456,789)";
str = str.replaceAll(".*\\((.*)\\).*","$1");
或者您可以通過以下方法使更換更快一些:
str = str.replaceAll(".*\\(([\\d,]*)\\).*","$1");
嘗試
"\\(([^)]+)\\)"
要么
int start = text.indexOf('(')+1;
int end = text.indexOf(')', start);
String num = text.substring(start, end);
private void showHowToUseRegex()
{
final Pattern MY_PATTERN = Pattern.compile("Your number is \\((\\d+),(\\d+),(\\d+)\\)");
final Matcher m = MY_PATTERN.matcher("Your number is (123,456,789)");
if (m.matches()) {
Log.d("xxx", "0:" + m.group(0));
Log.d("xxx", "1:" + m.group(1));
Log.d("xxx", "2:" + m.group(2));
Log.d("xxx", "3:" + m.group(3));
}
}
您會看到第一組是整個字符串,接下來的三組是您的數字。
String str = "Your number is (123,456,789)";
str = new String(str.substring(16,str.length()-1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.