2013-12-17 4 views
0

String.split()에 내가하고 싶은 것을하기 위해 고심하고 있습니다.단어 주위에 정규식을 사용하는 정규식

나는 공백으로 구분 된 일련의 단어를 입력했습니다. 어떤 단어는 특별한 기능을합니다. 그들은 다음과 같이 보입니다 : "special : word".

내가 내 정규식을 테스트하는 데 사용하고 입력 문자열은 다음과 같습니다

String str = "Hello wonderful special:world what a great special:day";

내가 str.split(regex)에서 좀하고 싶습니다 결과는 단어 "세상"과 "일"에 배열이다;

나는 lookahead (?<=special\:)(\w+)으로 해봤지만 찾고자하는 단어에서 문자열을 나눕니다. 이 표현식을 역으로 변환하여 내가 찾고있는 결과를 얻고 정확히 lookaheads와 reverse lookaheads가하는 일은 무엇입니까? 우리는 위와 같은 출력을 얻을도 여기에

String searchPattern1 = "Hello wonderful special:world what a great special:day"; 
    for(String i:searchPattern1.split("\\s")){ 
     if(i.contains(":")){ 
      System.out.println(i.split[1]); 
     } 
    } 

: 우리가 할 수있는 split()를 사용하여

world 
day 

:

+5

'split' 여기에 당신이 모든 당신의 특별한 단어를 찾을 수있는 방법의 예입니다 이것 때문에. 'Pattern'와'Matcher'를 사용하십시오. –

답변

0

PatternMatcher

String searchPattern = "Hello wonderful special:world what a great special:day"; 
    Pattern pa = Pattern.compile(":[a-zA-Z0-9]+"); 
    Matcher ma = pa.matcher(searchPattern); 
    while(ma.find()){ 
     System.out.println(ma.group().replaceFirst(":",""));  
    } 

출력 시도 . 이 경우 split를 사용

4

몇 가지 문제를 만들 것입니다 : 우리가 분할 후

Hello wonderful special:world what a great special:day 
^^^^^^^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^ 
  • 에 분할해야한다 부분에 맞게

    1. overcomplicated 정규식을 첫 번째 요소는 빈 문자열 "" 때문에 것 split은 마지막 빈 요소에서와 같이 첫 번째 빈 요소를 자르지 않으므로 결과는

      이됩니다.

    이 사용하기 더 직관적 인 접근을 방지하려면 대신 당신이 원하는 일부가 아닌 모든 것을 발견, 관심있는 부분만을 찾아이 사용을 PatternMatcher 클래스를 위해..

    String str = "Hello wonderful special:world what a great special:day"; 
    
    Pattern p = Pattern.compile("\\b\\w+:(\\w+)\\b");//word after : will be in group 1 
    Matcher m = p.matcher(str); 
    while(m.find()){//this will iterate over all found substrings 
        //here we can use found substrings 
        System.out.println(m.group(1)); 
    } 
    

    출력 :

    world 
    day 
    
  • +0

    하지만 다음과 같이 말할 수는 없습니다 : ':'와 ':'다음 단어 사이의 모든 단어 얻기? – JNK

    +0

    @JNK'단어 사이에 ':'와 ':' '뒤에 오는 모든 단어가 있지만 처음에는 특별한 : 단어가 없으므로'Hello wonderful special : '과 어떻게 일치할까요?또한 그러한 표현은 "전에는 : someWord"와 그 뒤에 ":''를 의미하지만, 동시에이 토큰을 원하지 않으므로 match에'someWord'를 포함하고 싶지 않습니다 분할에 의해 제거되었습니다. 그래서'(? <= : \\ w +). *? (? = :)'와 같은 look-around 메카니즘을 사용해야 할 것이다. 그러나 자바에서는 look-behind의 최대 길이를'\\ w +' 컴파일되지 않습니다. 이 경우 Pattern/Matcher 솔루션이 더 좋습니다. – Pshemo

    0

    사용 후두둑과 정규, 간단한 예를

    public static ArrayList<String> parseOut(String s) 
    { 
        ArrayList<String> list = new ArrayList<String>(); 
        String regex = "([:])(\\w+)"; 
        Pattern pattern = Pattern.compile(regex); 
        Matcher matcher = pattern.matcher(s); 
        while (matcher.find()){ 
         list.add(matcher.group().substring(1)); 
        } 
        return list; 
    } 
    
    내가 사용하지 않을