2017-03-18 7 views
5

नीचे पंक्ति में यदि हमारे पास सिंगल कोट (') है तो हमें इसे '||' से बदलना होगा '' लेकिन अगर हमारे पास दो बार उद्धरण है ('') तो यह होना चाहिए।रेगेक्स '(एकल कोट एक बार) को प्रतिस्थापित करने के लिए' '' ('सिंगल कोट दो बार)' '' '

मैंने कोड के टुकड़े के नीचे कोशिश की जो मुझे उचित आउटपुट नहीं दे रहा है।

कोड स्निपेट:

Your Form xyz doesn'||'''t show the same child''||'''s name as the name in your account with us. 

अपेक्षित परिणाम:

Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us. 
0 ऊपर कोड द्वारा

static String replaceSingleQuoteOnly = "('(?!')'{0})"; 
String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us."; 
System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''")); 

वास्तविक आउटपुट

नियमित अभिव्यक्ति बच्चे की जगह 'हैबच्चे के साथ' '||' 'केबच्चे का जैसा ही होना चाहिए।

उत्तर

5

आप इस के लिए lookarounds, जैसे उपयोग कर सकते हैं:

String replaceSingleQuoteOnly = "(?<!')'(?!')"; 
String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us."; 
System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''")); 
+0

धन्यवाद दर्शन से घिरा हुआ लगता है। मेरे पास अभी भी मेरे कोड में नियमित अभिव्यक्ति के साथ कुछ समस्याएं हैं जिन्हें मैंने यहां पोस्ट किया है: http://stackoverflow.com/q/42935679/3525348 क्या आप कृपया मेरी सहायता कर सकते हैं। –

4

एक नकारात्मक नज़र पीछे जोड़ने के आश्वासन एक और ' से पहले कोई ' चरित्र है कि और निकालने के अतिरिक्त कैप्चरिंग समूह ()

तो उपयोग करने के लिए (?<!')'(?!')

String replaceSingleQuoteOnly = "(?<!')'(?!')"; 
    String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us."; 
    System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''")); 

आउटपुट:

Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us. 

प्रति Apostrophe उपयोग के रूप में आप बस (?i)(?<=[a-z])'(?=[a-z]) उपयोग कर सकते हैं ' अक्षर

समाधान के लिए
String replaceSingleQuoteOnly = "(?i)(?<=[a-z])'(?=[a-z])"; 
    String line2 = "Your Form xyz doesN'T show the same child''s name as the name in your account with us."; 
    System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''")); 
संबंधित मुद्दे