将字符串中的所有单词/短语用引号引起来

问题描述 投票:0回答:1

输入是一个字符串,需要确保每个以引号(“)开头的单词或短语也以引号结尾,并且每个以引号(”)结尾的单词或短语也以引号开头。 单词/短语始终位于括号之间,并且 1 个括号内不能超过 1 个单词/短语。

示例:

  1. 输入:(“再见”)(十月)(得分)(再见”)(九月)(感谢)(负数)(家园)

    期望的输出:(“再见”)(十月)(得分)(“再见”)(九月)(感谢)(负面)(家园)

  2. 输入:(“提交”)(“再见”)(再见”)(迪拉姆)(重复)(取决于)(调查近电子邮件)(不要)(英镑”)

    所需的输出:(“提交”)(“再见”)(“再见”)(迪拉姆)(重复)(取决于)(调查近电子邮件)(不要)(“英镑”)

尝试了一些正则表达式和其他方法,但不起作用。

java string double-quotes
1个回答
0
投票

这是一个使用正则表达式模式的示例。

(?<=\().+?(?=\))
StringBuilder b = new StringBuilder();
String t, s = "(\"bye bye\") (october) (score) (bye\") (september) (thank) (negative) (homes)";
Pattern p = Pattern.compile("(?<=\\().+?(?=\\))");
Matcher m = p.matcher(s);
boolean x, y;
while (m.find()) {
    x = (t = m.group()).charAt(0) == '"';
    y = t.charAt(t.length() - 1) == '"';
    if (x && !y) t = t + '"';
    else if (!x && y) t = '"' + t;
    if (!b.isEmpty()) b.append(' ');
    b.append('(').append(t).append(')');
}

并且,这是使用 String#indexOf 方法的示例。

StringBuilder b = new StringBuilder();
String t, s = "(\"bye bye\") (october) (score) (bye\") (september) (thank) (negative) (homes)";
int i = -1, j;
boolean x, y;
while ((i = s.indexOf('(', i + 1)) != -1) {
    j = s.indexOf(')', i);
    t = s.substring(i + 1, j);
    x = t.charAt(0) == '"';
    y = t.charAt(t.length() - 1) == '"';
    if (x && !y) t = t + '"';
    else if (!x && y) t = '"' + t;
    if (!b.isEmpty()) b.append(' ');
    b.append('(').append(t).append(')');
}

输出

("bye bye") (october) (score) ("bye") (september) (thank) (negative) (homes)
("submit") ("bye bye") ("bye") (dirham) (repeat) (depends) (survey NEAR email) (dont) ("pounds")
© www.soinside.com 2019 - 2024. All rights reserved.