2012-05-03 3 views
3

У меня есть следующая строка «Class (102) (401)» и «Class (401)». Я хочу найти регулярное выражение, чтобы найти подстроку, которая всегда возвращает мне последнее значение скобки, в моем случае это ' 401) 'Java Regex, чтобы найти подстроку

Ниже мой код

Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))"); 
    Matcher mat = MY_PATTERN.matcher("Class (102) (401)"); 
    while (mat.find()){ 
     System.out.println(mat.group()); 
    } 

Он возвращается

- ( -) - ( -)

+2

Как о получении индекс last (and) и получить подстроку между ними? –

ответ

2

Вы можете использовать:

Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))"); 

See it

+0

Я попытался и он возвращает «Класс (102) (401)« Я хочу только последнее значение, которое находится в последнем скобке »401 ' –

+1

@Faisalkhan: Вам нужно использовать' group (1) '. См. Рабочую ссылку. – codaddict

+0

ОК это сработало и вернулось (401) –

1

Попробуйте это:

(?<=\()[^\)(]+(?=\)[^\)\(]+$) 

Пояснение:

<!-- 
(?<=\()[^\)(]+(?=\)[^\)\(]+$) 

Options:^and $ match at line breaks; free-spacing 

Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\()» 
    Match the character “(” literally «\(» 
Match a single character NOT present in the list below «[^\)(]+» 
    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
    A) character «\)» 
    The character “(” «(» 
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\)[^\)\(]+$)» 
    Match the character “)” literally «\)» 
    Match a single character NOT present in the list below «[^\)\(]+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
     A) character «\)» 
     A (character «\(» 
    Assert position at the end of a line (at the end of the string or before a line break character) «$» 
--> 
1

как насчет выражения: .*\\(([^\\(\\)]+)\\)[^\\(\\)]*$

он находит ( следует не-скобок [^\\(\\)] (нужная строка), за которыми следует ) и после этого только не-скобок допускается, поэтому он должен быть последним

Смежные вопросы