繁体   English   中英

如何在Java中查找表达式,求值和替换?

[英]How to find expression, evaluate and replace in Java?

我在字符串(来自文本文件)中有以下表达式:

{gender=male#his#her}
{new=true#newer#older}

我想:

  1. 查找该模式的出现{variable=value#if_true#if_false}
  2. 将这些变量临时存储为诸如StringvariableNamevariableValueifTrueifFalse等字段。
  3. 根据局部变量(例如,字符串性别=“ male”和字符串new =“ true”),基于variableNamevariableValue评估表达式。
  4. 最后根据(3)将模式替换为ifTrueifFalse

我应该以某种方式使用String.replaceAll()还是如何查找该表达式并保存其中的字符串? 谢谢你的帮助

更新

就像PHP的preg_match_all一样

更新2

我通过在下面作为答案发布时使用PatternMatcher解决了这一问题。

如果字符串始终采用这种格式,则可能要使用string.split('#') 这将在'#'分隔符中返回一个字符串数组(例如“ {gender = male#his#her}”。split('#')= {“ {gender = male”,“ his”,“ her}” };使用substring删除第一个和最后一个字符以除去大括号)

挣扎了一段时间后,我设法使用PatternMatcher使其工作如下:

// \{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.

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