简体   繁体   English

匹配字符串中的排他搜索组

[英]Matching exclusive search groups in a string

I've been struggling to come up with a reg-ex fix within my pg-promise library... 我一直在努力在pg-promise库中提出一个reg-ex修复程序...

It implements a formatting method which does a verification for a string to determine whether it is a simple one or not, based on the following rules: 它实现了一种格式化方法 ,该方法根据以下规则对字符串进行验证,以确定它是否是simple的字符串:

The string is defined as simple when: 在以下情况下,该字符串被定义为simple字符串:

  • it is a same-case single word, without spaces 它是一个大小写相同的单词,没有空格
  • it can contain underscores, and can even start with them 它可以包含下划线,甚至可以以下划线开头
  • it can contain digits and $, but cannot start with those 它可以包含数字和$,但不能以这些数字开头

Those a basically the rules for determining when an SQL alias needs to be wrapped in double-quotes or not. 这些基本上是确定何时将SQL别名需要用双引号引起来的规则。

So if I isolate the test logic: 因此,如果我隔离测试逻辑:

const m = name.match(/[a-z_][a-z0-9_$]*|[A-Z_][A-Z0-9_$]*/);

console.log(m && m[0] === name ? 'simple' : 'complex');

It passes tests in all cases, except when we have an underscore and then capital letters, like this: _A or __ABC . 它在所有情况下都通过测试,除非我们有下划线然后是大写字母,例如_A__ABC At the same time, it works for _a and __abc . 同时,它适用于_a__abc

How to change the regular expression to make it work for those special cases also? 如何更改正则表达式以使其也适用于那些特殊情况?

Thank you! 谢谢!

If you add metacharacters ^ (beginning of the string) and $ (end of the string) to your regular expression, it will work as expected for uppercase words too, and also let simplify condition on output: 如果在正则表达式中添加元字符^ (字符串的开头)和$ (字符串的结尾),则大写单词也可以正常使用,并且还可以简化输出条件:

const m = name.match(/^([a-z_][a-z0-9_$]*|[A-Z_][A-Z0-9_$]*)$/);

console.log(m ? 'simple' : 'complex');

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

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