[英]Java and regular expression, substring
I'm am tottaly lost when coming to regular expressions. 使用正则表达式时,我完全迷失了。 I get generated strings like: 我得到生成的字符串,如:
Your number is (123,456,789)
How can I filter out 123,456,789
? 如何过滤出123,456,789
?
You can use this regex for extracting the number including the commas 您可以使用此正则表达式提取包括逗号在内的数字
\(([\d,]*)\)
The first captured group will have your match. 捕获的第一个组将有您的比赛。 Code will look like this 代码将如下所示
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);
}
Explanation of the regex 正则表达式的说明
"\\(" + // 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
This will get you started http://www.regular-expressions.info/reference.html 这将使您开始使用http://www.regular-expressions.info/reference.html
String str="Your number is (123,456,789)";
str = str.replaceAll(".*\\((.*)\\).*","$1");
or you can make the replacement a bit faster by doing: 或者您可以通过以下方法使更换更快一些:
str = str.replaceAll(".*\\(([\\d,]*)\\).*","$1");
try 尝试
"\\(([^)]+)\\)"
or 要么
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));
}
}
You'll see the first group is the whole string, and the next 3 groups are your numbers. 您会看到第一组是整个字符串,接下来的三组是您的数字。
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.