2016-11-08 1 views
0

나는 StringList<String>입니다. 나는 String에서 앞뒤 두 문자를 포함한 내 List<String의 내용을 추출하고 싶습니다.문자열에서 일치하는 하위 문자열을 추출하는 중

예를 검토 한 결과는 StackOverflow입니다. 구분 기호가 없으므로 어떤 형태로든 일치가 표시된다는 경계가 없습니다. RegEx를 사용하여 답변을 요청하고 검토했으며이를 수행하는 방법이 될 수 있다고 생각하지만 어떻게해야합니까?

내가 String toParse = "Parse this to grab the &@[email protected]& variable";이고 List<String>ClaimNumber이 있으면 객체 지향 솔루션이 있습니까?

+0

당신이 원하는 정규 표현식이 단지'(..ClaimNumber ..)'또는''(.?. ClaimNumber?.?)''0 '또는'1 '의 앞/뒤 문자로 케이스를 잡는 것처럼 들리는 것 같습니다. – CollinD

+0

@CollinD 네, 맞습니다. 변수'ClaimNumber'는 앞뒤 두 글자를 포함하는 'List '에 들어 있습니다. – Mushy

답변

1

다음의 방법은 정확하게 동적 검색 값 인용의 추가의 suggestion by CollinD 다음, 그것을 할 것이다

private static List<String> extract(String input, List<String> keywords) { 
    StringJoiner regex = new StringJoiner("|"); 
    for (String keyword : keywords) 
     regex.add(".." + Pattern.quote(keyword) + ".."); 
    List<String> result = new ArrayList<>(); 
    for (Matcher m = Pattern.compile(regex.toString()).matcher(input); m.find();) 
     result.add(m.group()); 
    return result; 
} 

테스트

System.out.println(extract("Parse this to grab the &@[email protected]& variable", 
          Arrays.asList("ClaimNumber"))); 
System.out.println(extract("The quick brown fox jumps over the lazy dog", 
          Arrays.asList("fox", "i"))); 

출력

[&@[email protected]&] 
[quick, n fox j] 
관련 문제