简体   繁体   中英

Regular expression: word between spaces

Sry for stupid question, but there is an example: 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).

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 [] )

Since you are not separating the words with other punctuations. So I believe only using \\S is sufficient for you.

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.

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. Because the space before the CASE was picked by the SELECT . You have mandatory space( \\s ) at the both sides of the word(ie \\s\\w*\\s ). In other words your regex has overlapping.

Updated regex:

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.

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]

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: \\[[^]]+]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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