在目标串词:This is a new pen.
正则表达式 - 选择不完全或部分匹配
我的目标是把上面的字符串到This is a __ __.
用JavaScript这样的:
const str = "This is a new pen."
const newStr = str.replace(/[^this |is |a |an |the |are |.\s]+/ig, ' __ ').trim()
可悲的是,正则表达式以上使用是错误的,因为它输出This is a ne __ __ en.
因为“an”和“the”包含在正则表达式中。
我该如何达到目标,并且仍然在正则表达式中保留“an”和“the”?
编辑:
我修改了原始字符串 测试的an
,and
,that
和's
的效果,除了a
,this
,the
等:
const str = "This is a new pen and that's an old business book."
const newStr = str.replace(/[^this |is |\'s |and |that |a |an |the |are |.\s]+/ig, ' __ ').trim()
所以正则表达式现在比较长,但仍然存在问题。一个理想的结果应该是This is a __ __ and that's an __ __ __.
这个正则表达式并没有做你期望的。方括号构成一个字符集;集合内字符的排序无关紧要。 – jasonharper
@jasonharper我真的不擅长正则表达式。添加方括号是为了显示'^'**的效果,而不是**选择。 – sijane
@sijane我已经大量更新了我的答案,现在完成了,我不知道你是否收到通知,但是你可能想要查看它。请告诉我,如果它不符合你对撇号的需求,我可能有一些时间来改进它,如果需要的话。 – Aaron