I need a help in building the regex for following pattern where I have to collect the string in a particular pattern.
Sample Input String:
*!
hostname ${hostname} !
!
!
ip name-server ${ip-name-server}
no ipv6 cef
!
!
voice class codec 1
codec preference 1 ${codec-pref-1} codec preference 2 ${codec-pref-2} codec preference 3 ${codec-pref-3} !
!
session target dns:${session-targ-DNS} dtmf-relay rtp-nte*
The output should be hostname, ip-name-server, codec-pref-1, codec-pref-2, codec-pref-3, session-targ-DNS,
i.e the string which is covered in the format ${string} should be collected and retrieved.
I tried code as below
public void fetchKeyword(String inputString) {
String inputString1 = inputString.replace("\n", " ");
Pattern p = Pattern.compile("\\${$1} ");
Matcher m = p.matcher(inputString1);
int i=0;
while(m.find()){
System.out.println(m.group(i));
i++;
}
}
Also I tried patterns likes .${.*}, (.)${.*?} etc but no result came as expected. I got exceptions like below
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1
\${$1}
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.closure(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at myUtil.ReplaceString.fetchKeyword(ReplaceString.java:70)
at myUtil.ReplaceString.main(ReplaceString.java:20)
Can anyone please help on the same?
{and}are special in regular expressions (they allow you to specify limited repetitions, likex{3,5}(x repeated 3 to 5 times)). So you need to escape them as well, not just the$.