如何解决正则表达式选择带有空格的单词来代替
我在JS中有一个字符串,需要在其中将'
添加到值中。
示例:task: task one,client: Mr jhon
将转换为
task:'task one',client: 'Mr Jhon'
将这些字符串视为用户输入的搜索查询。然后将其发送到支持者进行搜索。值需要包含在'
复杂性
-
taskname: one two three,client: Mr Jhon
不能超过2个字 -
taskname: one two,client: Mr Jhon
超过1个空格 -
taskname:one,client: Mr Jhon
可以是没有空格的单字 -
priority:1,groupname: Mr Singh
的名称可以是任何东西 -
priority:1,task: Mr Singh,planet:pluto,done:Yes
可以有2个以上的数据点
我正在使用以下代码在Javascript中转换字符串。
let myStr = `taskname: task one`
myStr = `${myStr},`
const finalStr = myStr.replace(/:((?:\w*\s*)+),/g,`:'$1',`)
console.log(finalStr)
问题1:正则表达式是否有效?
PS:我将在Node JS服务器中使用它。
解决方法
也许这样的事情对您有用
let myStr = `taskname: task one,client: Mr jhon
taskname: one two three,client: Mr Jhon there can be more than 2 words
taskname: one two,client: Mr Jhon more than 1 space
taskname:one,client: Mr Jhon can be singe word without space
priority:1,groupname: Mr Singh the name of can be anything
priority:1,task: Mr Singh,planet:pluto,done:Yes There can be more than 2 data points`;
const finalStr = myStr.replace(
/((?<=^\w+\:)(.*?)(?=\,)|(?<=\w+\:)(.*?)(?=\,)|(?<=\w+\:)(.*?)$)/gim,(match) => `'${match.trim()}'`
);
console.log(finalStr);
,
这应该可以正常工作:
let myStr = `taskname: one two three,client: Mr Jhon
taskname: one two,client: Mr Jhon
taskname:one,client: Mr Jhon
priority:1,groupname: Mr Singh
priority:1,done:Yes`;
const finalStr = myStr.replace(/([^,:\n]+):\s*([^,:\n]+)/g,`$1:'$2'`)
console.log(finalStr)
输出:
taskname:'one two three',client:'Mr Jhon'
taskname:'one two',client:'Mr Jhon'
taskname:'one',client:'Mr Jhon'
priority:'1',groupname:'Mr Singh'
priority:'1',task:'Mr Singh',planet:'pluto',done:'Yes'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。