Reputation: 2655
I want to select those who doesn't begin or end with space.
Test String:
ad
bui sfa
daf
a
fa
12
Attempted Regex (with no match ;(... ):
^[^\s]*.*[^\s]*$
Here is the link.
Upvotes: 2
Views: 2294
Reputation: 626896
Your regex ^[^\s]*.*[^\s]*$
does not work because you applied *
quantifier to the [^\s]
negated character classes matching any symbol but whitespace, thus making this optional. Also, your input looks to be multiline, so in the online regex tester, you'd need to specify the /m
multuline flag to see if the lines match your pattern. Also, the pattern requires at least two symbols to be present in the input string, but you also have a a
line (containing 1 symbol) - and it wouldn't get matched.
You can use
^(?!\s|.*\s$).*$
See the regex demo. Note the use of the /m
multiline flag (necessary if your input is multiline). This pattern allows any string that does not begin or end with a whitespace.
A more detailed explanation:
^
- start of a line(?!\s|.*\s$)
- a negative lookahead that fails a match if the string starts (due to the first \s
) or (|
) ends (due to .*\s$
) with whitespace.*$
- actually matches a line up to the end.Upvotes: 4
Reputation: 10149
Try the regex: ^\S+(.*\S+)?$
.
\s
is a character class, that contains whitespaces. \S
is the negated class. It stands for non-whitespaces. ^
matches at the beginning of a line.^\S+
matches one or more non-whitspaces at the beginning of a line(.*\S+)?
:
\S+
is again one or more non-whitspaces (...)?
the question marks makes the part inside the parentheses optional. This makes the line a
match.$
means "at the end of a line".Upvotes: 3