简体   繁体   English

Java字符串/正则表达式替换

[英]Java String/Regex Replace

I'm quite new to regex. 我是正则表达式的新手。 Not sure how to do the follow: 不确定如何执行以下操作:

Replace ":p_id" with a specific value. 将“:p_id”替换为特定值。

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. 例如,当我只想用一个值替换“:p_id1”时,它也用不是我想要的相同值替换“:p_id10”。

It's also possible for the ":p_id"'s to have punctuation before or after them eg "=:p_id1)" 也可能在“:p_id”之前或之后标点,例如“ =:p_id1)”

Any advice? 有什么建议吗?

Use the \\b (word boundary) operator 使用\\b (单词边界)运算符

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

See Pattern > Boundary matchers 参见Pattern > 边界匹配器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM