user3714417
user3714417

Reputation: 51

detect $character java regular expression

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

Answers (2)

zx81
zx81

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):

\$\{[^}]*\}
  • In Java, we need to further escape the backslashes, yielding \\$\\{[^}]*.
  • Likewise \$\{\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 brace

Upvotes: 1

Christian Tapia
Christian Tapia

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

Related Questions