2011-11-28 25 views
5

Tôi có văn bản với nhiều cụm từ #{key}. Ví dụ:Làm thế nào để thay thế tất cả # {key} thành chuỗi?

Lorem ipsum dolor sit amet, consectetur adipisicing #{key1}. Proin nibh 
augue, suscipit a, scelerisque #{key1}, lacinia in, mi. Cras vel #{key2}. 
Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. 
Quisque semper #{key3} at risus. 

tôi cần phải thay thế tất cả #{key} giá trị tương ứng với messageSource.getMessage(key, null, locale) (messageSourceorg.springframework.context.MessageSource), nhưng tôi không giỏi regex. Làm thế nào để xây dựng đúng biểu thức chính quy?

Ví dụ:

#{texts.appName} need to replace with messageSource.getMessage("texts.appName", null, locale); 
#{my.company} need to replace with messageSource.getMessage("my.company", null, locale); 
+0

Xem câu trả lời của tôi! :) – HashimR

+0

nhìn vào lớp String trong api nó sẽ cho bạn biết tất cả những gì bạn cần – lancegerday

Trả lời

3

Giả sử key chỉ là một giữ chỗ cho bất kỳ tên regex của bạn sẽ là một cái gì đó như thế này: #\{([\w\.]+)\}

Điều này có nghĩa: bất kỳ chuỗi ký tự chữ hoặc dấu chấm (\w\., tương đương với a-zA-Z0-9_\.) giữa #{} được trả lại dưới dạng nhóm 1.

Bây giờ bạn cần phải tạo ra một khớp và duyệt qua các trận đấu, giải nén phím và thay thế phù hợp với thông điệp của bạn:

String input = "Lorem ipsum dolor sit amet, consectetur adipisicing #{key1}. " + 
    "Proin nibh augue, suscipit a, scelerisque #{key1}," + 
    "lacinia in, mi. Cras vel #{key2}. Etiam pellentesque aliquet tellus." + 
    " Phasellus pharetra nulla ac diam. Quisque semper #{key3} at risus."; 
StringBuffer result = new StringBuffer(); 

Pattern p = Pattern.compile("#\\{([\\w\\.]+)\\}"); 
Matcher m = p.matcher(input); 

while(m.find()) {  
    //extract the message for key = m.group(1) here 
    //i'll just mark the found keys 
    m.appendReplacement(result, "##" + m.group(1) + "##");  
} 
m.appendTail(result); 

System.out.println(result); //output: ... consectetur adipisicing ##key1## ... etc. 
2

Give này regex thử:

#{([^}]+)} 
0

Sử dụng yourString.replaceAll("\\#\\{key\\}", messageSource.getMessage(key, null, locale))

Dấu gạch chéo ngược đầu tiên là để thoát khỏi dấu gạch chéo ngược thứ hai từ chuỗi giải thích của java. Thứ hai là để thoát dấu '#' (hoặc '{', '}' các dấu hiệu) để diễn giải regex.

0

Thông tin cho bạn đây. Ví dụ làm việc:

Pattern p = Pattern.compile("\\Q#{\\E([^.]+)\\Q}\\E"); 
Matcher m = p.matcher(yourString); 
Pattern tempPattern = Pattern.compile("([#{][^.]+[}])"); 
Matcher tempMatcher = tempPattern.matcher(yourString); 


while(m.find() && tempMatcher.find()) {  

    String textToReplace = messageSource.getMessage(m.group(1), null, locale); 
    yourString = yourString.replace(tempMatcher.group(1), textToReplace); 
} 

System.out.println(yourString); 

Hy vọng điều này sẽ hữu ích!

Các vấn đề liên quan