如果领先的数字不匹配?

时间:2022-02-01 11:38:03

I created a small RegEx in order to find some variable names in a string:

我创建了一个小RegEx,以便在字符串中找到一些变量名:

([a-zA-Z][a-zA-Z0-9_]+)

In my case, a variable can have integers and letters + the underscore character, but it shouldn't start by a number.

在我的例子中,一个变量可以有整数和字母+下划线字符,但是它不应该从一个数字开始。

The issue is that in this string:

问题是在这个字符串中:

"whateverTextBefore,246myVariableName25"

It will match myVariableName25, leaving the 246 before. I would like not to match this at all.

它将匹配myVariableName25,剩下246之前。我不想和这个完全匹配。

I tried this pattern too:

我也尝试过这种模式:

([^0-9]*[a-zA-Z][a-zA-Z0-9_]+)

To specify no leading number, but I get the same result.

若要指定不带序号,则会得到相同的结果。

So how can I make this RegEx work to just refuse match at all if there are leading numbers?

那么,如果有领先的数字,我怎么能让这个RegEx工作到拒绝匹配呢?

Note that in the example, it is a comma before, but it could be any specific character, among others:

注意,在本例中,它之前是一个逗号,但它可以是任何特定字符,其中包括:

,.<>/?:;'"[]{})(-+=

2 个解决方案

#1


3  

You can use word boundary \b.

你可以使用单词边界\b。

\b([a-zA-Z][a-zA-Z0-9_]+)\b

Demo

演示

Also, note that [a-zA-Z0-9_] can be replaced by \w.

另外,请注意[a-zA-Z0-9_]可以用\w代替。

\b([a-zA-Z]\w+)\b

Demo

演示

To allow a single alphabet, + quantifier can be replaced by *.

要允许一个字母,+量词可以被*代替。

\b([a-zA-Z]\w*)\b
             ^

#2


0  

Use this!

使用这个!

/\b([^,0-9]\w*?)\b/g

Demo: https://regex101.com/r/eU4nP1/1

演示:https://regex101.com/r/eU4nP1/1

Don't forget the g modifier so it will match multiple results. Every language has a different way to add modifier. This is for PHP.

不要忘记g修饰符,它将匹配多个结果。每种语言都有不同的添加修饰符的方法。这是为PHP。

Don't forget to exclude , or it will be included in the result.

不要忘记排除,否则它将包含在结果中。

#1


3  

You can use word boundary \b.

你可以使用单词边界\b。

\b([a-zA-Z][a-zA-Z0-9_]+)\b

Demo

演示

Also, note that [a-zA-Z0-9_] can be replaced by \w.

另外,请注意[a-zA-Z0-9_]可以用\w代替。

\b([a-zA-Z]\w+)\b

Demo

演示

To allow a single alphabet, + quantifier can be replaced by *.

要允许一个字母,+量词可以被*代替。

\b([a-zA-Z]\w*)\b
             ^

#2


0  

Use this!

使用这个!

/\b([^,0-9]\w*?)\b/g

Demo: https://regex101.com/r/eU4nP1/1

演示:https://regex101.com/r/eU4nP1/1

Don't forget the g modifier so it will match multiple results. Every language has a different way to add modifier. This is for PHP.

不要忘记g修饰符,它将匹配多个结果。每种语言都有不同的添加修饰符的方法。这是为PHP。

Don't forget to exclude , or it will be included in the result.

不要忘记排除,否则它将包含在结果中。