我有一个名为“ string1”的字符串,

string1 = "Mr. Jorge Alexa Narvaez is a former Canadian cricketer and a politician.";


我还有另一个名为“ string2”的字符串,该字符串仅包含由“ <NOUN> and </NOUN>”标记包围的字符串,并用空格分隔。

string2 = "<NOUN>Jorge Alexa Narvaez</NOUN> <NOUN>Canadian</NOUN>";


请注意,第二个字符串可以没有任何带有名词标记的单词(基于'string1',例如:如果string1具有3个名词,则string2将具有被名词标记包围的3个相同名词)
我想将标签添加到'string1'并使string1如下所示,

string1 = "Mr. <NOUN>Jorge Alexa Narvaez</NOUN> is a former <NOUN>Canadian</NOUN> cricketer and a politician.";


我只想用<NOUN>Jorge Alexa Narvaez</NOUN> and <NOUN>Canadian</NOUN>替换'Jorge Alexa Narvaez'和'Canadian'

谁能告诉我该怎么做?

最佳答案

可以按照以下步骤完成,

 Pattern p = Pattern.compile("<NOUN>(.*?)</NOUN>");
    Matcher m = p.matcher(string2);
    while(m.find()) {
        string1= string1.replaceAll(m.group(1),m.group(0));
    }

09-05 03:11