avatar
regex: what does [^ ] mean?# Unix - 噫吁兮,危乎高哉
f*y
1
s/^([^ ]+) +([^ ]+)/$2 $1/;
the expression above is to swap the first two words..
what does [^ ] mean? it matches a space at the
first charactor position of a string?
avatar
T*r
2
[^ ] means NOT space.

【在 f***y 的大作中提到】
: s/^([^ ]+) +([^ ]+)/$2 $1/;
: the expression above is to swap the first two words..
: what does [^ ] mean? it matches a space at the
: first charactor position of a string?

avatar
f*y
3
Thank you very much for you answer.
$testswap = "one two three";
$testswap =~ s/^(.+) +(.+)/$2 $1/;
print "$testswap\n";
the screen output is: "three one two"
why? I expected "two one three"..
Thanks.

【在 T********r 的大作中提到】
: [^ ] means NOT space.
avatar
c*j
4

This is confusing, you use "." to match any character including " "
and excluding "\n", so every parts of your string will be treated as $1
until it meets the last non-space part (from your " +").
say,
s/^(.+) +(.+)/
1. anything from beginning should be assigned to $1 from code "/^(.+)"
2. anything to the end should be assigned to $2 from code "(.+)/"
3. there should be some space between $1 and $2 from code " +"
result: $1 == "one two"
$2 == "three"

【在 f***y 的大作中提到】
: Thank you very much for you answer.
: $testswap = "one two three";
: $testswap =~ s/^(.+) +(.+)/$2 $1/;
: print "$testswap\n";
: the screen output is: "three one two"
: why? I expected "two one three"..
: Thanks.

avatar
f*y
5
you are right..
Thank you very much.

【在 c****j 的大作中提到】
:
: This is confusing, you use "." to match any character including " "
: and excluding "\n", so every parts of your string will be treated as $1
: until it meets the last non-space part (from your " +").
: say,
: s/^(.+) +(.+)/
: 1. anything from beginning should be assigned to $1 from code "/^(.+)"
: 2. anything to the end should be assigned to $2 from code "(.+)/"
: 3. there should be some space between $1 and $2 from code " +"
: result: $1 == "one two"

avatar
p*s
6

Regexp matching is greedy, that is, it will try to match
the longest pattern.
Thus, "^(.+) +" matches "one two ", and $1 is "one two".
The next "(.+)" matches "three", and $2 is "three".

【在 f***y 的大作中提到】
: Thank you very much for you answer.
: $testswap = "one two three";
: $testswap =~ s/^(.+) +(.+)/$2 $1/;
: print "$testswap\n";
: the screen output is: "three one two"
: why? I expected "two one three"..
: Thanks.

avatar
f*y
7
that's right.. i forgot it's greedy.
Thank you.

【在 p****s 的大作中提到】
:
: Regexp matching is greedy, that is, it will try to match
: the longest pattern.
: Thus, "^(.+) +" matches "one two ", and $1 is "one two".
: The next "(.+)" matches "three", and $2 is "three".

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。