简体   繁体   English

Javascript:如何编写正则表达式来检查符号是否被所有出现的空格包围

[英]Javascript : How to write a regex to check if a symbol is surrounded by space for all occurences

The colon ':' in the sentence should be surrounded by space for all of its occurrences.句子中的冒号 ':' 应该用空格包围它的所有出现。

I have a string "Yes I Do : things that have:fun"我有一个字符串“Yes I Do : things that have:fun”

My regex should return false, I have tried the below which is checking is checking first occurence, if found it is returning true.我的正则表达式应该返回 false,我尝试了下面的检查是检查第一次出现,如果发现它返回 true。

/(\s:\s)/.test("sd : sds:sds")

If you want a pure regex solution then use this alternation based regex to find out invalid inputs :如果你想要一个纯正则表达式解决方案,那么使用这个基于交替的正则表达式来找出无效的输入

/(?:^|\S):|:(?:$|\S)/

RegEx Demo正则表达式演示

RegEx Details:正则表达式详情:

  • (?:^|\\S) : Match start or a non-whitespace (?:^|\\S) : 匹配开始或非空格
  • : : Match a colon : : 匹配一个冒号
  • | : OR : 或者
  • : : Match a colon : : 匹配一个冒号
  • (?:$|\\S) : Match end or a non-whitespace (?:$|\\S) : 匹配结尾或非空格

 const regex = /(?:^|\\S):|:(?:$|\\S)/; const arr = [`Yes I Do : things that have :fun`, `Yes I Do : things that have: fun`, `: fun`, `fun :`, `Yes I Do : things that have : fun`, ` : fun`, `fun : `]; for (var i=0; i<arr.length; i++) { console.log(regex.test(arr[i]), '::', arr[i]); }

你可以做完全相反的事情,搜索被非空格字符包围的符号(在符号之前或之后)。

!/\S:|:\S/.test("sd : sds:sds")

Add the global flag ( g ) to the end of your RegEx and check for non-space chars.将全局标志( g )添加到 RegEx 的末尾并检查非空格字符。

 console.log(!/\\S:|:\\S/g.test("sd : sds:sds")); console.log(!/\\S:|:\\S/g.test("sd : sds : sds"));

This will check the full string.这将检查完整的字符串。

You can achieve it by regex and simple logic.您可以通过正则表达式和简单的逻辑来实现。 This is not the proper way to achieve use case but maybe it can help.这不是实现用例的正确方法,但也许可以提供帮助。

 function check(str) { let reg = / : /gi; let match = str.match(reg); if (match && match.length == str.split(":").length - 1) { return true; } else { return false } } console.log(check("sdf : sdf")); console.log(check("sdf: sdf")); console.log(check("sdf : sdf:")); console.log(check("sdf : sdf sdfds : sdf"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM