[英]Java String Replace Regex
I am doing some string replace in SQL on the fly. 我正在动态进行SQL中的某些字符串替换。
MySQLString = " a.account=b.account ";
MySQLString = " a.accountnum=b.accountnum ";
Now if I do this 现在如果我这样做
MySQLString.replaceAll("account", "account_enc");
the result will be 结果将是
a.account_enc=b.account_enc
(This is good) (很好)
But look at 2nd result 但是看第二个结果
a.account_enc_num=a.account_enc_num
(This is not good it should be a.accountnum_enc=b.accountnum_enc
) (这不好,应该是a.accountnum_enc=b.accountnum_enc
)
Please advise how can I achieve what I want with Java String Replace. 请告知如何使用Java String Replace实现我想要的功能。
Many Thanks. 非常感谢。
From your comment: 根据您的评论:
Is there anyway to tell in Regex only replace a. 无论如何在正则表达式中告诉只替换一个。 account =b. 帐户 = b。 account or a. 帐户或 accountnum =b. accountnum = b。 accountnum . 帐号 。 I do not want accountname to be replace with
_enc
我不想帐户名是与替代_enc
If I understand correctly you want to add _enc
part only to account
or accountnum
. 如果我理解正确,则只想将_enc
部分添加到account
或accountnum
。 To do this you can use 为此,您可以使用
MySQLString = MySQLString.replaceAll("\\baccount(num)?\\b", "$0_enc");
(num)?
mean that num
is optional so regex will accept account
or accountnum
表示num
是可选的,因此正则表达式将接受account
或accountnum
\\\\b
at start mean that there can be no letters, numbers or " _
" before account
so it wont accept (affect) something like myaccount, or my_account. \\\\b
开头表示account
前不能有字母,数字或“ _
”,因此它不会接受(影响)诸如myaccount或my_account之类的内容。
\\\\b
at the end will prevent other letters, numbers or " _
" after account or accountnum. 末尾的\\\\b
将防止在帐户或accountnum之后出现其他字母,数字或“ _
”。
It's hard to extrapolate from so few examples, but maybe what you want is: 很难从这么几个例子中推断出来,但是也许您想要的是:
MySQLString = MySQLString.replaceAll("account\\w*", "$0_enc");
which will append _enc
to any sequence of letters, digits, and underscores that starts with account
. 这将追加_enc
的英文字母,数字的任何序列和下划线与启动account
。
try 尝试
String s = " a.accountnum=b.accountnum ".replaceAll("(account[^ =]*)", "$1_enc");
it means replace any sequence characters which are not ' ' or '=' which starts the word "account" with the sequence found + "_enc". 这意味着将所有不是''或'='的序列字符替换为以找到的序列+“ _enc”开头的单词“ account”。
$1 is a reference to group 1 in regex; $ 1是对正则表达式中第1组的引用; group 1 is the expression in parenthesis (account[^ =]+), ie our sequence 第1组是括号中的表达式(account [^ =] +),即我们的序列
See http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html for details 有关详细信息,请参见http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.