Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
8  
Just go follow a regex tutorial, it will teach you all of the basics. –  Supericy May 14 '13 at 8:17
2  
What have you tried so far? –  Shobit May 14 '13 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) –  pn7a May 14 '13 at 8:19

3 Answers 3

up vote 1 down vote accepted

Use the \b (word boundary) operator

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

See Pattern > Boundary matchers

share|improve this answer
    
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! –  sb89 May 14 '13 at 8:55

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
share|improve this answer
    
It's also possible for the ":p_id"'s to have punctuation before or after them e.g. =:p_id1 –  kocko May 14 '13 at 8:46

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.