[英]Regular expression: word between spaces
Sry for stupid question, but there is an example: http://jsfiddle.net/rb98M/ 对愚蠢的问题感到抱歉,但是有一个示例: http : //jsfiddle.net/rb98M/
var q = 'SELECT CASE WHEN STATE IN ';
q = q.replace(/(^|\s)\w*(\s|$)/g, function(match) { return match.toLowerCase(); });
alert(q);
I have a string and i want to make lowerCase each word, that's between white spaces (and could be in start of line and end). 我有一个字符串,我想使每个单词都使用lowerCase,它在空格之间(并且可以在行的开头和结尾)。
But, my result is: 但是,我的结果是:
select CASE when STATE in
and that's my problem. 那是我的问题。 Why is it so? 为什么会这样呢?
Edit I expect to pass SELECT * FROM [Users] u
and get select * from [Users] u
and etc (including each SQL statement and exclude any table names and properties in []
) 编辑我希望传递SELECT * FROM [Users] u
并获得select * from [Users] u
等(包括每个SQL语句,并排除[]
任何表名和属性)
Since you are not separating the words with other punctuations. 由于您没有用其他标点符号来分隔单词。 So I believe only using \\S
is sufficient for you. 因此,我相信仅使用\\S
就足够了。
q = q.replace(/(\S+)/g, function(match)
In your case it was not working because the \\s\\w*\\s was eating the SELECT
(with space at end) from the input and the CASE
wasn't have enough space( \\s
) before it. 在您的情况下,它不起作用,因为\\ s \\ w * \\ s正在吃掉输入中的SELECT
(结尾处有空格),而CASE
之前没有足够的空间( \\s
)。
Here is how your input was matched using the regex: 这是使用正则表达式匹配输入的方式:
SELECT CASE WHEN state IN
^ m1 ^ ^ m2 ^ ^m3^
Its just ignored the CASE
ad the state
words from the regex. 它只是忽略了CASE
广告和来自正则表达式的state
字。 Because the space before the CASE
was picked by the SELECT
. 因为CASE
之前的空间是由SELECT
。 You have mandatory space( \\s
) at the both sides of the word(ie \\s\\w*\\s
). 你必须强制空间( \\s
在字的两边)(即\\s\\w*\\s
)。 In other words your regex has overlapping. 换句话说,您的正则表达式有重叠。
q = q.replace(/(?:\s|^)(\w+)(?=\s|$)/g, function(match)
You can use this code and put in the capturing group all parts you want to skip: 您可以使用此代码并将要跳过的所有部分放入捕获组:
var q = 'SELECT * FROM [Users] u aNd GeT sElEct * from [Users] U';
q = q.replace(/(\[[^\]]+\])|\w+/g, function(m, g1) {
return (g1) ? m : m.toLowerCase(); });
The method toLowerCase()
is applied to the whole match only if the capturing group is defined. 仅当定义了捕获组时,才会将toLowerCase()
方法应用于整个匹配项。
I used \\w
to make the pattern shorter, but since it is useless to replace digits, lowercase letters and underscores, you can replace it with [AZ]
我使用\\w
缩短了模式,但由于它无法代替数字,小写字母和下划线,因此可以将其替换为[AZ]
pattern detail: 图案细节:
\[ # a literal [
[^\]]+ # character class with all characters except ] (repeated one or more times)
\] # a literal ]
Note that you don't need to escape the closing square bracket (or only for very old versions of internet explorer):), you can write: \\[[^]]+]
请注意,您无需转义右方括号(或仅适用于非常旧版本的Internet Explorer):),可以这样写: \\[[^]]+]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.