正则表达式用于从字符串中删除单引号(所有格名词除外)?
Regex for removing single quotes from string except for possessive nouns?
我在 Java 中有以下正则表达式:
String regex = "[^\s\p{L}\p{N}]";
Pattern p = Pattern.compile(regex);
String phrase = "Time flies: "when you're having fun!" Can't wait, 'until' next summer :)";
String delimited = p.matcher(phrase).replaceAll("");
现在这个正则表达式删除所有非空格和非字母数字。
Input: Time flies: "when you're having fun!" Can't wait, 'until' next summer :)
Output: Time flies when youre having fun Cant wait until next summer
问题是,我想保留单词上的单引号,例如 you're、can't 等。但想删除句子末尾或单词周围的单引号,比如'hello'。
这就是我想要的:
Input: Time flies: "when you're having fun!" Can't wait, 'until' next summer :)
Output: Time flies when you're having fun Can't wait until next summer
如何更新我当前的正则表达式才能执行此操作?我需要保留 \p{L} 和 \p{N},因为它必须适用于多种语言。
谢谢!
这应该做你想做的,或者接近:
String regex = "[^\s\p{L}\p{N}']|(?<=(^|\s))'|'(?=($|\s))";
正则表达式有三个选项,由 |
分隔。它将匹配:
- 任何不是 space、字母、数字或引号的字符。
- 引号,如果它前面是行的开头或 space(因此,引号在单词的开头)。这使用 正向回顾。
- 一个引号,如果它后跟行尾或 space(因此,引号在单词的末尾)。这使用 正向先行.
它适用于您提供的示例。它可能无法按您想要的方式工作的地方是,如果您有一个单词在一侧带有引号,而另一侧没有:"'Tis a shame that we couldn't visit James' house"
。由于 lookahead/behind 只查看引号前后的字符,而不会向前看(例如)单词开头的引号是否跟在单词末尾的引号这个词,它将删除 'Tis and James' 上的引号。
我在 Java 中有以下正则表达式:
String regex = "[^\s\p{L}\p{N}]";
Pattern p = Pattern.compile(regex);
String phrase = "Time flies: "when you're having fun!" Can't wait, 'until' next summer :)";
String delimited = p.matcher(phrase).replaceAll("");
现在这个正则表达式删除所有非空格和非字母数字。
Input: Time flies: "when you're having fun!" Can't wait, 'until' next summer :)
Output: Time flies when youre having fun Cant wait until next summer
问题是,我想保留单词上的单引号,例如 you're、can't 等。但想删除句子末尾或单词周围的单引号,比如'hello'。 这就是我想要的:
Input: Time flies: "when you're having fun!" Can't wait, 'until' next summer :)
Output: Time flies when you're having fun Can't wait until next summer
如何更新我当前的正则表达式才能执行此操作?我需要保留 \p{L} 和 \p{N},因为它必须适用于多种语言。
谢谢!
这应该做你想做的,或者接近:
String regex = "[^\s\p{L}\p{N}']|(?<=(^|\s))'|'(?=($|\s))";
正则表达式有三个选项,由 |
分隔。它将匹配:
- 任何不是 space、字母、数字或引号的字符。
- 引号,如果它前面是行的开头或 space(因此,引号在单词的开头)。这使用 正向回顾。
- 一个引号,如果它后跟行尾或 space(因此,引号在单词的末尾)。这使用 正向先行.
它适用于您提供的示例。它可能无法按您想要的方式工作的地方是,如果您有一个单词在一侧带有引号,而另一侧没有:"'Tis a shame that we couldn't visit James' house"
。由于 lookahead/behind 只查看引号前后的字符,而不会向前看(例如)单词开头的引号是否跟在单词末尾的引号这个词,它将删除 'Tis and James' 上的引号。