Reputation: 51
i have to find a word like ${test} from text file. and will replace the based on some criteria. in the regular express '$' have meaning of search till the end of the line.
what is the regular expression to detect like ${\w+}.
Upvotes: 0
Views: 163
Reputation: 41838
[^}]*
rather than \w+
?
You might want to consider using [^}]*
rather than \w+
. The former matches any chars that are not a closing brace, so it would allow test-123, which the second would reject. Of course that may just be what you want.
Let's assume this is the raw regex (see what matches in the demo):
\$\{[^}]*\}
\\$\\{[^}]*
.\$\{\w+\}
would have to be used as \\$\\{\\w+\}
Replacing the Matches in Java
String resultString = subjectString.replaceAll("\\$\\{[^}]*\}", "Your Replacement");
Iterating through the matches in Java
Pattern regex = Pattern.compile("\\$\\{[^}]*\}");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
// the current match is regexMatcher.group()
}
Explanation
\$
matches the literal $
\{
matches an opening brace[^}]*
matches any chars that are not a closing brace\}
a closing braceUpvotes: 1
Reputation: 34146
You can try using this regex:
"\\$\\{\\w+\\}"
and the method String#replaceAll(String regex, String replacement)
:
String s = "abc ${test}def"; // for example
s = s.replaceAll("\\$\\{\\w+\\}", "STACKOVERFLOW");
Upvotes: 1