I am trying to match (once or twice) any instance of fixed|local|scroll But I do not want to capture the trailing space. I thought I fixed this by putting in (?: ... \s*) but it is still capturing that trailing space.

For example:

Here is my regex:

((?:(?:fixed|local|scroll)\s*){1,2})

Here is the string:

background: url("my image.jpg") left right 2px 50% 75% repeat scroll border-box padding-box;

Here is the match:

`scroll `

Expected:

`scroll`

Btw I am using the following site to test my regex:

有帮助吗?

解决方案 2

You can do this:

\s*((?:\s*?\b(?:fixed|local|scroll)\b){1,2})

or

\s*((?:\s*?(?:fixed|local|scroll)){1,2})

(if word boundaries are not needed)

Explanation: since \s* is by default greedy, all leading white spaces are "eaten" before the catpure group.

其他提示

In the regex you gave, the outer-most group is the only capturing group and that contains the \s*.

You could try something like this which is a bit longer:

(fixed|scroll|local)(\s+(fixed|scroll|local))?

An occurrence of (fixed|scroll|local) followed by one more optional one. Duplicating it like that makes things easier because it allows you to say "whitespace is valid between matches but not after".

Another option would just be to deal with the trailing space programmatically using trim.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top