[英]Regular expression to replace apostrophe
I need to replace all punctuation symbols in given string except " ' " when it is before text, after and between.我需要替换给定字符串中除“ ' ”之外的所有标点符号,当它位于文本之前、之后和之间时。 For replacing I use
replaceAll()
with regex "[.,?;:?/]|(.=.['])([^A-Za-z]')"
.对于替换,我使用
replaceAll()
和正则表达式"[.,?;:?/]|(.=.['])([^A-Za-z]')"
。 But it doesn't work with 5th example.但它不适用于第 5 个示例。 Any ideas how to do it?
任何想法如何做到这一点?
Examples:例子:
" ' " -> " " “ ' ”->“”
" ''' " -> " " “ ''' ”->“”
" text'text " -> " text'text " “文本'文本”->“文本'文本”
" text' " -> " text' " “文字' ”->“文字' ”
" 'text " -> " 'text " “ '文本”->“ '文本”
The regex provided is syntactically invalid (2 opening parentheses, 1 closing), but that may be a typo.提供的正则表达式在语法上无效(2 个左括号,1 个右括号),但这可能是一个错字。
The suggested solution (regex only):建议的解决方案(仅限正则表达式):
(?<![a-zA-Z])'(?![a-zA-Z])
A negative lookbehind checking for absence of text followed by the apostrophe and a negative lookahead again checking for the absence of text.一个否定的lookbehind 检查是否没有文本,然后是撇号,一个否定的lookahead 再次检查是否没有文本。
You might want to adjust the character class defining 'text'.您可能需要调整定义“文本”的字符 class。
Demo available here (Regex 101) .此处提供演示 (Regex 101) 。
Match any of the symbols, or match an apostrophe that is not preceded or succeeded by a word character.匹配任何符号,或匹配前面或后面没有单词字符的撇号。
Those are zero-width negative lookbehind assertion and zero-width negative lookahead assertion.这些是零宽度负后瞻断言和零宽度负前瞻断言。 Most regex implementations have them, but some do not.
大多数正则表达式实现都有它们,但有些没有。 You can only put constant-size expressions within them.
您只能在其中放置常量大小的表达式。
[.,?;:?/]|(?<!\w)'(?!\w)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.