Java String/Regex Replace

I'm quite new to regex. Not sure how to do the follow:

Replace ":p_id" with a specific value.

For example when I simply want to replace ":p_id1" with a value, it also replaced ":p_id10" with the same value which is not what I want.

It's also possible for the ":p_id"'s to have punctuation before or after them e.g. "=:p_id1)"

Any advice?

Answers


Use the \b (word boundary) operator

myString.replaceAll(":p_id1\\b","some replacement");

See Pattern > Boundary matchers


You could use a negative lookahead at the end of your Pattern.

For instance:

Pattern pattern = Pattern.compile(":p_id\\d(?!\\d)");
String example = ":p_id1 :p_id10";
Matcher matcher = pattern.matcher(example);
while (matcher.find()) System.out.println(matcher.group());

Output:

:p_id1

Here's the pattern I made:

 ^[=]{0,1}:p_id1\b[=]{0,1}

This matches strings like:

:p_id1
=:p_id1
:p_id1=

but doesn't match (for instance):

:p_id10

Need Your Help

Send email to multiple recipients (with recipients from textbox.value)

vba outlook outlook-vba

I am trying to create a taskmangement in Outlook with Custom Forms.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.