[英]How to find expression, evaluate and replace in Java?
I have the following expressions inside a String (that comes from a text file): 我在字符串(来自文本文件)中有以下表达式:
{gender=male#his#her}
{new=true#newer#older}
And I would like to: 我想:
{variable=value#if_true#if_false}
{variable=value#if_true#if_false}
variableName
, variableValue
, ifTrue
, ifFalse
as String
s. String
的variableName
, variableValue
, ifTrue
, ifFalse
等字段。 variableName
and variableValue
according to local variables (like String gender = "male" and String new = "true"). variableName
和variableValue
评估表达式。 ifTrue
or ifFalse
according to (3). ifTrue
或ifFalse
。 Should I use String.replaceAll()
in some way, or how do I look for this expression and save the strings that are inside? 我应该以某种方式使用
String.replaceAll()
还是如何查找该表达式并保存其中的字符串? Thanks for your help 谢谢你的帮助
UPDATE 更新
It would be something like PHP's preg_match_all . 就像PHP的preg_match_all一样 。
UPDATE 2 更新2
I solved this by using Pattern
and Matcher
as I post as an answer below. 我通过在下面作为答案发布时使用
Pattern
和Matcher
解决了这一问题。
If the strings always take this format, then string.split('#')
is probably the way to go. 如果字符串始终采用这种格式,则可能要使用
string.split('#')
。 This will return an array of strings in the '#' separator (eg "{gender=male#his#her}".split('#') = {"{gender=male", "his", "her}"}; use substring
to remove the first and last character to get rid of the braces) 这将在'#'分隔符中返回一个字符串数组(例如“ {gender = male#his#her}”。split('#')= {“ {gender = male”,“ his”,“ her}” };使用
substring
删除第一个和最后一个字符以除去大括号)
After strugling for a while I managed to get this working using Pattern
and Matcher
as follows: 挣扎了一段时间后,我设法使用
Pattern
和Matcher
使其工作如下:
// \{variable=value#if_true#if_false\}
Pattern pattern = Pattern.compile(Pattern.quote("\\{") + "([\\w\\s]+)=([\\w\\s]+)#([\\w\\s]+)#([\\w\\s]+)" + Pattern.quote("\\}"));
Matcher matcher = pattern.matcher(doc);
// if we'll make multiple replacements we should keep an offset
int offset = 0;
// perform the search
while (matcher.find()) {
// by default, replacement is the same expression
String replacement = matcher.group(0);
String field = matcher.group(1);
String value = matcher.group(2);
String ifTrue = matcher.group(3);
String ifFalse = matcher.group(4);
// verify if field is gender
if (field.equalsIgnoreCase("Gender")) {
replacement = value.equalsIgnoreCase("Female")?ifTrue:ifFalse;
}
// replace the string
doc = doc.substring(0, matcher.start() + offset) + replacement + doc.substring(matcher.end() + offset);
// adjust the offset
offset += replacement.length() - matcher.group(0).length();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.