模式匹配之前的任何字母数字文本 - 在字符串中

时间:2022-09-13 07:44:47

I try to get any alphanumeric word or text in a string before the negative sign - for example:

我尝试在负号前面的字符串中输入任何字母数字或文字 - 例如:

earth-green, random-stuff, coffee-stuff, another-tag

I try to match earth random coffee another

我尝试将另一种土豆随机咖啡与之匹配

I tried the following regex:

我尝试了以下正则表达式:

(\w*[^][\-])

However, it matches earth- random- coffee- another-

然而,它匹配地球随机咖啡 - 另一个 -

This DEMO shows the situation. there you may notice that earth- random- coffee- another- are highlighted while I don't want include the negative sign - in the highlighting.

这个DEMO展示了这种情况。那里你可能会注意到地球随机咖啡 - 另一个 - 突出显示,而我不想要包含负号 - 突出显示。

4 个解决方案

#1


This is a good example to use positive look ahead regex.

这是使用正向前瞻性正则表达式的一个很好的例子。

You can use a regex like this:

你可以使用这样的正则表达式:

(\w+)(?=-)

模式匹配之前的任何字母数字文本 - 在字符串中

Working demo

On the other hand, the problem in your regex was that you were putting the hypen and ^ within the capturing group:

另一方面,你的正则表达式中的问题是你把hypern和^放在捕获组中:

(\w*[^][\-])
     ^---^---- Here (btw... you don't need [^])

You had to use this one instead

你不得不使用这个

(\w+)-

Working demo

#2


You can just add a word boundary and - to bookmark what you want:

你可以添加一个单词边界和 - 为你想要的书签:

\b(\w+)-

Demo

#3


>>> x = 'earth-green, random-stuff, coffee-stuff, another-tag'
>>> re.compile('(\w+)-\w+').findall(x)
['earth', 'random', 'coffee', 'another']
>>>

A lot of good examples with diverse use cases regex howtos

很多很好的例子都有不同的用例正则表达式

#4


You can match it like this.

你可以像这样匹配它。

   my $string = "earth-green, random-stuff, coffee-stuff, another-tag";
    while ($string =~ m/[\w]*-/g)
    {
        my $temp = $&;
        $temp =~s/-//;
        print "$temp\n";
    }

Hope this helps.

希望这可以帮助。

#1


This is a good example to use positive look ahead regex.

这是使用正向前瞻性正则表达式的一个很好的例子。

You can use a regex like this:

你可以使用这样的正则表达式:

(\w+)(?=-)

模式匹配之前的任何字母数字文本 - 在字符串中

Working demo

On the other hand, the problem in your regex was that you were putting the hypen and ^ within the capturing group:

另一方面,你的正则表达式中的问题是你把hypern和^放在捕获组中:

(\w*[^][\-])
     ^---^---- Here (btw... you don't need [^])

You had to use this one instead

你不得不使用这个

(\w+)-

Working demo

#2


You can just add a word boundary and - to bookmark what you want:

你可以添加一个单词边界和 - 为你想要的书签:

\b(\w+)-

Demo

#3


>>> x = 'earth-green, random-stuff, coffee-stuff, another-tag'
>>> re.compile('(\w+)-\w+').findall(x)
['earth', 'random', 'coffee', 'another']
>>>

A lot of good examples with diverse use cases regex howtos

很多很好的例子都有不同的用例正则表达式

#4


You can match it like this.

你可以像这样匹配它。

   my $string = "earth-green, random-stuff, coffee-stuff, another-tag";
    while ($string =~ m/[\w]*-/g)
    {
        my $temp = $&;
        $temp =~s/-//;
        print "$temp\n";
    }

Hope this helps.

希望这可以帮助。