Reputation: 77
I have this program
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String subjectString = "<Name>DGAU</Name><SSN>123456789</SSN><OtherDetails></OtherDetails>";
String REPLACE = "#";
Pattern regex = Pattern.compile("<SSN>\\d{9}");
Matcher regexMatcher = regex.matcher(subjectString);
subjectString = regexMatcher.replaceAll(REPLACE);
System.out.println(subjectString);
}
}
When i run the above program
The Output formed is
<Name>DGAU</Name>#</SSN><OtherDetails></OtherDetails>
How to have output as
<Name>DGAU</Name><SSN>#</SSN><OtherDetails></OtherDetails>
Have the SSN # in between .
Upvotes: 0
Views: 39
Reputation: 10360
Use Regex
(<SSN>)\d{9}
and replace it with
$1#
Explanation:
(<SSN>)
- matches <SSN>
and captures it in Group 1\d{9}
- matches 9 digitsNow replace the entire match with $1#
i.e, contents of Group 1 followed by #
Note: In Java, you need to escape \
with another \
. So, your regex is (<SSN>)\\d{9}
Upvotes: 3