0

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?

2
  • 8
    Just go follow a regex tutorial, it will teach you all of the basics. Commented May 14, 2013 at 8:17
  • Providing the code you actually use for this procedure would help us understand what you are looking for. I would also suggest to take a look at this Java tutorial. It might help you understand how to fix it on your own (it feels better to do it yourself) Commented May 14, 2013 at 8:19

3 Answers 3

1

Use the \b (word boundary) operator

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

See Pattern > Boundary matchers

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That worked. I did have "\\b:p_id1\\b" before but that didn't seem to work. I definitely have to go and read some regex tutorials again!
0

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

1 Comment

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.