JavaScript 正则表达式(当且仅当)

标签 javascript regex

我刚刚完成了所有“简单”的 CoderByte 挑战,现在回去看看是否有更有效的方法来回答问题。我正在尝试为“SimpleSymbol”提出一个正则表达式。

(Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.)

我最初通过遍历整个字符串来回答这个问题,当找到一个字母时,测试两边是否存在“+”。我认为如果我可以用正则表达式测试字符串会更容易,比如

str.match(/\+[a-zA-Z]\+/g)

这不太行得通。我正在尝试查看匹配是否仅在字符串中的所有字符都满足条件时才返回 true。例如,由于 '+d+' 和 '+c+',该方法将在字符串“++d+===+c++==a”上返回 true。但是,根据原始问题,它应该返回 false,因为 'a' 并且没有周围的 '+'。

有什么想法吗?

最佳答案

编辑:@Marc 提出了一个非常好的观点。最简单的方法是使用搜索违规

[^+][a-zA-Z]|[a-zA-Z][^+]

或类似的东西。这将找出所有违反 规则的地方——当一个字母出现在不是+ 的东西旁边时。如果匹配,则可以返回 false,知道存在违规。否则,返回 true

原答案:

这是一个正则表达式——我将在下面对其进行解释。请记住,您必须转义 +,因为它是一个特殊字符!

^([^a-zA-Z+]|(\+[a-zA-Z]\+)|[+])*$

^ // start of the string
[^a-zA-Z+] // any character except a letter or a + (1)
| // or
(\+[a-zA-Z]\+) // + (letter) + (2)
| //or
[+] // plus (3)
)*$ // repeat that pattern 0 or more times, end
  • 这背后的逻辑是:跳过所有与您的字符串无关的字符。 (1)
  • 如果我们有一个 +(字母)+,那很好。捕获那个。 (2)
  • 如果我们有一个 + all 本身,那也很好。 (3)
  • 没有包围 + 的字母将失败。

关于JavaScript 正则表达式(当且仅当),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18499510/

相关文章:

javascript - ReactJS - 在不提供 HTTP 文件的情况下无法运行 babel 代码

javascript - 在 AngularJS 中使用来自 JSON 的深层嵌套对象 - 奇怪的行为

python正则表达式删除匹配的括号文件

从列中删除 .x

Python - 使用 RegEx 从字符串中提取模式

javascript - 如何在多个选择中保留现有文件选择

javascript - 我的 jQuery 在 Chrome 中工作,但在 IE 11 中不工作

javascript - 尝试限制 ASP.NET MVC 中 int 数据类型的大小限制

mysql - MySQL 中搜索查询中 'dd/dd/dd' 的正则表达式

php preg_grep 和元音变音/重音