根据字符数和空格数使用正则表达式拆分字符串 [英] Split a string with regex based on number of characters and spaces

查看:210
本文介绍了根据字符数和空格数使用正则表达式拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据一些字符将一个字符串拆分成一个数组而不会删掉一个字。

I need to split a string into an array, based on a number of characters and without cutting off a word.

我一直在使用它:

var charPerLine = 17;
var regex = new RegExp('^(.{'+charPerLine+'}\\S*\\s+', 'g');
var output = str.replace(regex, "$&@").split(/\s+@/);

问题使用此代码有时我会得到一个超过17个字符的字符串,如果空格接近最新字符。

The issue with this code is that sometimes I get a string longer than 17 characters, in the case the space was close to the latest character.

例如,

var str = "I want you to do something else instead.";

分为:

var output = ["I want you to do something", "else instead."]

但第一个字符串超过17个字符,我需要拆分如:

But the first string is more than 17 characters, I need it to be split such as:

var output = ["I want you to do", "something else", "instead."]

它还必须与标点符号和单/双引号一起使用

It must also work with punctuations and single/double quotes

有什么建议吗?

推荐答案

(?=(\b.{1,17}\b))\1

您可以使用此替换通过 $ 1 \ n 。参见演示。

You can use this and replace by $1\n.See demo.

https://regex101.com/r/ff7iZp/1

这篇关于根据字符数和空格数使用正则表达式拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆