javascript正则表达式只返回字母 [英] javascript regex to return letters only

查看:166
本文介绍了javascript正则表达式只返回字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串可以是A01,B02,C03,也可能是AA18。我以为我可以使用正则表达式来获取字母并在我的正则表达式上工作,因为我没有做太多的事情。我写了这个函数:

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:

function rowOffset(sequence) {
              console.log(sequence);
            var matches = /^[a-zA-Z]+$/.exec(sequence);
            console.log(matches);
            var letter = matches[0].toUpperCase();
            return letter;
}

var x = "A01";
console.log(rowOffset(x));

我的匹配继续为空。我这样做了吗?看看这篇文章,我认为正则表达式是正确的:只有字符az,AZ的正则表达式

My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z

推荐答案

您的主要问题是使用 ^ $ 正则表达式模式中的字符。 ^ 表示字符串的开头, $ 表示结束,因此你模式正在寻找一个 ONLY 一组一个或多个字母,从字符串的开头到结尾。

Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.

此外,如果你想获得每个单独的实例这些字母,你想在正则表达式模式的末尾加入全局指标( g ): / [a-zA-Z ] + /克。离开这意味着它只会找到模式的第一个实例,然后停止搜索。 。 。添加它将匹配所有实例。

Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.

这两个更新应该让你去。

Those two updates should get you going.

编辑:

此外,您可能希望使用 match()而不是 exec()。如果你有一个多个值的字符串(例如,A01,B02,C03,AA18), match()将在数组中返回所有内容,而 exec()仅匹配第一个。如果它只有一个值,那么 exec()就可以了(你也不需要全局标志)。

Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).

如果你想使用 match(),你需要稍微改变你的代码顺序:

If you want to use match(), you need to change your code order just a bit to:

var matches = sequence.match(/[a-zA-Z]+/g);

这篇关于javascript正则表达式只返回字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆