Java и регулярное выражение, подстрока - PullRequest
1 голос
/ 15 ноября 2011

Я полностью потерялся при переходе к регулярным выражениям. Я получаю сгенерированные строки, такие как:

Your number is (123,456,789)

Как я могу отфильтровать 123,456,789?

Ответы [ 5 ]

3 голосов
/ 15 ноября 2011

Вы можете использовать это регулярное выражение для извлечения числа, включая запятые

\(([\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

Это поможет вам начать http://www.regular -expressions.info / reference.html

1 голос
/ 15 ноября 2011
String str="Your number is (123,456,789)";
str = str.replaceAll(".*\\((.*)\\).*","$1");                    

или вы можете сделать замену немного быстрее, выполнив:

str = str.replaceAll(".*\\(([\\d,]*)\\).*","$1");                    
0 голосов
/ 15 ноября 2011
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 группы - это ваши числа.

0 голосов
/ 15 ноября 2011
String str = "Your number is (123,456,789)";
str = new String(str.substring(16,str.length()-1));
0 голосов
/ 15 ноября 2011

попробуй

"\\(([^)]+)\\)"

или

int start = text.indexOf('(')+1;
int end = text.indexOf(')', start);
String num = text.substring(start, end);
...