0

我正在尝试在程序从非结构化文本中检索它们后给我的名称,并以用户指定的格式显示它们“First MI. Last”或“Last, First MI”。有任何想法吗?到目前为止,它会检查字符串中是否存在逗号。如果是这样,我想切换字符串中单词的顺序并删除逗号,如果有一个中间首字母并且它后面不包含句点,我想添加一个。

if (entity instanceof Entity) {
    // if so, cast it to a variable
    Entity ent = (Entity) entity;

    SName name = ent.getName();
    String nameStr = name.getString();
    String newName = "";

    // Now you have the name to mess with
    // NOW, this is where i need help
    if (choiceStr.equals("First MI. Last")) {
        String formattedName = WordUtils
                .capitalizeFully(nameStr);
        for (int i = 0; i < formattedName.length(); i++) {

            if (formattedName.charAt(i) != ',') {
                newName += formattedName.charAt(i);
            }
        }
    }
    name.setString(newName);
    network.updateConcept(ent);
4

2 回答 2

3

使用正则表达式和String.replaceAll

"Obama, Barack H.".replace("(\\w+), (\\w+) (\\w\\.)", "$2 $3 $1")

结果是Barack H. Obama

于 2012-05-11T01:34:41.517 回答
2

这会更容易substring。这假定格式有效(您必须检查)。

//Separate the names
String newName;
String lastName = name.substring(0, name.indexOf(","));
String firstName = name.substring(name.indexOf(",")+1);

//Check for a space indicating a middle Name
//Check to see if the middle name already has the period if not add it
if(firstName.trim().contains(" ") && !firstName.contains(".")) {
   firstName += ".";
}

newName = firstName + " " + lastName;

//Set the name to whatever you're using

请注意,如果名称允许包含,这将不起作用"," " " or "."

于 2012-05-11T01:29:46.167 回答