当我来到正则表达式时,我完全迷失了。 我得到了生成的字符串,如:
Your number is (123,456,789)
如何过滤掉123,456,789
?
答案 0 :(得分:3)
您可以使用此正则表达式来提取包括逗号
在内的数字\(([\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
答案 1 :(得分:1)
String str="Your number is (123,456,789)";
str = str.replaceAll(".*\\((.*)\\).*","$1");
或者您可以通过以下方式更快地进行替换:
str = str.replaceAll(".*\\(([\\d,]*)\\).*","$1");
答案 2 :(得分:0)
试
"\\(([^)]+)\\)"
或
int start = text.indexOf('(')+1;
int end = text.indexOf(')', start);
String num = text.substring(start, end);
答案 3 :(得分:-1)
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));
}
}
您会看到第一组是整个字符串,接下来的3组是您的数字。
答案 4 :(得分:-3)
String str = "Your number is (123,456,789)";
str = new String(str.substring(16,str.length()-1));