2016-08-19 3 views
0

내가 문자열을 분할 [,.!?;~]를 사용하려면,하지만 난 예를 들면 그 자리에 [,.!?;~]을 유지하려는 :이 예입니다이 형식으로 문자열을 분할하는 정규식을 작성하는 방법은 무엇입니까?

,하지만 충분하지

하는 방법이다

[This is the example,, but it is not enough] // length=2 
[0]=This is the example, 
[1]=but it is not enough 

당신이 쉼표가 그 자리에 여전히 볼 수 있듯이. 이 정규식 (?<=([,.!?;~])+)으로이 작업을 수행했습니다. 하지만[,.!?;~] 뒤에 특수 단어 (예 : but)가 오는 경우 문자열의 해당 부분을 분할하지 마십시오. 예 :

이 문장을이 형식으로 분할하고 싶습니다. 사람이 도울 수 있다면 첫 번째 문장하는 int 분할되지 않은이 부분을 참조 (양식을하지만) 할 수 있도록, 그

[0]=I want this sentence to be split into this form, but how to do. 
[1]=So if anyone can help, 
[2]=that will be great 

좋을 것입니다.

+3

사용 부정적인 내다. '(? <= [,.!?; ~]) (?!하지만)'. –

답변

2

은 내가 사용했습니다 :

  1. 긍정적 Lookbehind (?<=a)b을 구분 기호를 유지합니다.
  2. 네가티브 Lookahead a(?!b)은 중지 단어를 배제합니다.

제공되는 RegEx를 사용한 후 RegEx (?!\\s*(but|and|if))을 어떻게 추가했는지 주목하십시오. pipe symbol으로 구분 된 괄호 안에 배제한 모든 중지 단어를 넣을 수 있습니다 (예 : but, if).

또한 구분 기호가 여전히 있음을 확인하십시오.

출력

Count of tokens = 3 
I want this sentence to be split into this form, but how to do. 
So if anyone can help, 
that will be great 

코드

import java.lang.*; 

public class HelloWorld { 
    public static void main(String[] args) { 
     String str = "I want this sentence to be split into this form, but how to do. So if anyone can help, that will be great"; 
     //String delimiters = "\\s+|,\\s*|\\.\\s*"; 
     String delimiters = "(?<=,)"; 

     // analyzing the string 
     String[] tokensVal = str.split("(?<=([,.!?;~])+)(?!\\s*(but|and|if))"); 

     // prints the number of tokens 
     System.out.println("Count of tokens = " + tokensVal.length); 

     for (String token: tokensVal) { 
      System.out.println(token); 
     } 
    } 
} 
+1

고마워요! 그것이 바로 원하는 것입니다. –

관련 문제