正则表达式 - 在有点的地方拆分,但如果引号出现在点之后,则在那里拆分
Regex - Splitting where there is a dot, but if quote mark appears after dot, split there
我必须拆分这个字符串(引号 included 在字符串中):"This is a test. I need this to be splitted." And here is one with a question?
想要的结果:['"This is a test.', 'I need this to be splitted."', 'And here is one with a question?']
描述:
问题是我需要在有 .!?;
的任何地方拆分我的文本,但是如果这些符号中的任何一个右侧出现引号,我需要在 之后进行拆分 引号。我想保留所有标点符号或引号。
代码:
现在我正在这样做:
var str = '"This is a test. I need this to be splitted."';
let arr = str.match(/[^ ].+?(\.(?!;)|[?!:;])/g);
...但这还没有完全奏效。
split
和
/(?<=[.!?;])\s+(?=[^\s"])|(?<=")\s+/
参见 proof。这会拆分带有空格的字符串,这些空格要么以 .!?;
字符开头,后跟一个非空格和双引号的字符,或者以 "
.
开头的空格
JavaScript:
console.log(
'"This is a test. I need this to be splitted." And here is one with a question?'.split(/(?<=[.!?;])\s+(?=[^\s"])|(?<=")\s+/)
)
对于示例数据,一种选择是使用 alternation |
with lookarounds and then use split。
说明
(?<=[.!?;])
正面回顾,断言直接在左边的是 .!?;
之一
匹配 space(您也可以使用 \s+
来表示 1+ whitspace 个字符,这也可能匹配换行符)
(?!")
否定前瞻,断言直接在右边的不是"
|
或
(?<=")
正向后视,断言直接在左边的是 "
。如果是,则匹配 space.
const regex = /(?<=[.!?;]) (?!")|(?<=") /g;
const str = `"This is a test. I need this to be splitted." And here is one with a question?`;
console.log(str.split(regex));
我必须拆分这个字符串(引号 included 在字符串中):"This is a test. I need this to be splitted." And here is one with a question?
想要的结果:['"This is a test.', 'I need this to be splitted."', 'And here is one with a question?']
描述:
问题是我需要在有 .!?;
的任何地方拆分我的文本,但是如果这些符号中的任何一个右侧出现引号,我需要在 之后进行拆分 引号。我想保留所有标点符号或引号。
代码: 现在我正在这样做:
var str = '"This is a test. I need this to be splitted."';
let arr = str.match(/[^ ].+?(\.(?!;)|[?!:;])/g);
...但这还没有完全奏效。
split
和
/(?<=[.!?;])\s+(?=[^\s"])|(?<=")\s+/
参见 proof。这会拆分带有空格的字符串,这些空格要么以 .!?;
字符开头,后跟一个非空格和双引号的字符,或者以 "
.
JavaScript:
console.log(
'"This is a test. I need this to be splitted." And here is one with a question?'.split(/(?<=[.!?;])\s+(?=[^\s"])|(?<=")\s+/)
)
对于示例数据,一种选择是使用 alternation |
with lookarounds and then use split。
说明
(?<=[.!?;])
正面回顾,断言直接在左边的是.!?;
之一
\s+
来表示 1+ whitspace 个字符,这也可能匹配换行符)(?!")
否定前瞻,断言直接在右边的不是"
|
或(?<=")
正向后视,断言直接在左边的是"
。如果是,则匹配 space.
const regex = /(?<=[.!?;]) (?!")|(?<=") /g;
const str = `"This is a test. I need this to be splitted." And here is one with a question?`;
console.log(str.split(regex));