2017-12-27 1 views

답변

0

그냥이 3 캡처 그룹을 연결 : 문자열에서 언급

(\[{)\s\w+\s*("\w+":\s*"\w+",)\s*\w+\s("\w+":\s*"\w+"}]) 
0
String text = "some value [{ hello \"name\": \"value\", xyz \"hello\": \"value\"}] hello"; 

Pattern pattern = Pattern.compile("(\\[[^\\[\\]]+\\])"); 
Matcher matcher = pattern.matcher(text); 

LinkedHashMap<String, String> result = new LinkedHashMap<>(); 

while (matcher.find()) { 
    String textSub = matcher.group(); 
    Pattern patternSub = Pattern.compile("(\"(?<name>[^\"]+)\": ?\"(?<value>[^\"]+)\")"); 
    Matcher matcherSub = patternSub.matcher(textSub); 
    while (matcherSub.find()) 
     result.put(matcherSub.group("name"), matcherSub.group("value")); 

} 
result.forEach((name, value) -> System.out.println("name:" + name + ", value: " + value)); 
0

지수가 탈출해야합니다. 적절한 정규식 패턴

String s = "some value [{ hello \"name\": \"value\", xyz \"hello\": \"value\"}] hello"; 

사용 완전히 대체 방법 :이처럼

사실 그냥 키/값 쌍마다 일치 일치하는 그룹과 정규식을 사용할 필요가
s = s.replaceAll(".*(\\[\\{\\s\\w+\\s(.*?),\\s\\w+\\s(.*?)\\}\\]).*", "\\[\\{$2,$3\\}\\]"); 
0

, 이것은이다 regex you need :

(\"\\w+\"\\s*:\\s*\"?\\w+\"?)

그리고 이것은 당신이 테스트 할 수있는 전체 JSON 배열을 얻을 수있는 코드를 어떻게해야입니다 this live working Demo :

final String regex = "(\"\\w+\"\\s*:\\s*\"?\\w\\s]+\"?)"; 
final String string = "some value [{ hello \"name\": \"value\", xyz \"hello\": \"value\" hello \"age\":778 and hello}] "; 

final Pattern pattern = Pattern.compile(regex); 
final Matcher matcher = pattern.matcher(string); 
String output = "[{"; 

List<String> allMatches = new ArrayList<String>(); 

while (matcher.find()) { 
    allMatches.add(matcher.group(0)); 
} 

Iterator<String> it = allMatches.iterator(); 
while(it.hasNext()){ 
    output += (String) it.next(); 
    if(it.hasNext()){ 
     output += ", "; 
    } 
} 
output += "}]"; 

참고 :이 정규식 numbersdates 및뿐만 아니라 strings을 포함한 값의 다른 유형을 수용하는 것을

참고. 답에 대한

+1

안녕 감사, 값이 다음과 같은 공간이 포함 된 경우 "이름 :"안녕하세요! 안녕하세요 이름 "이 경우 경기가 아래와 같이 발견된다" ":" – Raju

+0

@Raju 안녕하세요 제가 정규식이 너무 업데이트가 공백으로 문자열을 매 크로하고 데모도 업데이트했습니다.) –

+0

@Raju 편집을 마쳤습니까? –

관련 문제