简体   繁体   English

使用正则表达式替换字符

[英]character getting replaced by using regular expression

String tempprop="(kfsdk)#";
tempprop = tempprop.replaceAll("[^\\s]\\)\\#", "\"?if_exists}");
System.out.println("1"+tempprop+"2");

I want the output as 我希望输出为

1(kfsdk"?if_exists}2 1(kfsdk“?if_exists} 2

but the output of this regular expression is 但是这个正则表达式的输出是

1(kfsd"?if_exists}2 1(kfsd“?if_exists} 2

Last k is getting trimmed, and I don't know why. 最后k个被修整了,我不知道为什么。

if tempprop is ( )#, then output should be 1( )#2 only without "?if_exists This regular expression adds "?if_exists if no space is present else it returns the string as it is 如果tempprop为()#,则输出应仅为1()#2,且不带“?if_exists "?if_exists如果没有空格,则此正则表达式添加"?if_exists ,否则它将按原样返回字符串

You could use a negative lookbehind instead of [^\\\\s] because it causes some effect in the final output. 您可以使用负向后看而不是[^\\\\s]因为这会在最终输出中产生一些影响。 That is, lookarounds does a zero width match. 也就是说,环顾四周的宽度为零。

String tempprop="(kfsdk)#";
tempprop = tempprop.replaceAll("(?<!\\s)\\)#", "\"?if_exists}");
System.out.println("1"+tempprop+"2");

Output: 输出:

1(kfsdk"?if_exists}2

Explanation: 说明:

  • (?<!\\s) Negative lookbehind which asserts what preceeds is not a space character. (?<!\\s)负向后看,断言前面没有空格字符。
  • \\)# Matches the literal )# symbols. \\)#匹配文字)#符号。

To exclude [^\\s] from your capture, use the regex (?<![^\\s])\\)\\# . 要从捕获中排除[^\\s] ,请使用正则表达式(?<![^\\s])\\)\\# Another option is to enforce letters using (?<=\\w)\\)\\# or even forcing an opening bracket by using 另一种选择是使用(?<=\\w)\\)\\#强制使用字母,甚至使用强制使用左括号

out = str.replaceAll("(\\(\\w+)\\)\\#", "$1\"?if_exists}");

See here for more on lookaround (look-behind and look-ahead). 请参阅此处以获取更多有关环视(后视和前瞻)的信息。

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

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