[英]regex to get first 3 letters and all numbers from a string in javascript
I am trying my hand at regex for the first time. 我是第一次在正则表达式上尝试。 The input is a day of the week and a number, like SUNDAY 2
or WEDNESDAY 25
. 输入的是星期几和一个数字,例如SUNDAY 2
或WEDNESDAY 25
。 I need a regex to make the output SUN 2
or WED 25
, i tried ^.{0,3}\\d+
but it does not seem to work. 我需要一个正则表达式以使输出SUN 2
或WED 25
,我尝试了^.{0,3}\\d+
但似乎不起作用。 Would someone mind helping me out? 有人介意帮我吗?
Things to notice: The date can have either 1 or 2 digits 注意事项:日期可以是1或2位数字
Working example on regexr.com: http://regexr.com/3fcg7 regexr.com上的工作示例: http: //regexr.com/3fcg7
First of all, you're missing the space \\s
: 首先,您缺少空格\\s
:
^.{0,3}\\s?\\d+
But, that's still not enough, you need to acknowledge and ignore all the following letters, and then grab only the numbers. 但是,这还不够,您需要确认并忽略以下所有字母,然后仅获取数字。 You can do this with regex groups. 您可以使用正则表达式组来执行此操作。 (They're zero based, with Zero being the entire match, then 1,2, etc would be the groups you create): (它们是从零开始的,零是整个匹配项,然后是1,2,等等是您创建的组):
(^[AZ]{3})[AZ]*\\s?(\\d)+
That's (First group) any capital letter (at the beginning of the string) 3 times, then any capital letter 0 or more times, then a space, then (second group) any digit 1 or more times. 这是(第一组)任何大写字母(在字符串的开头)3次,然后是任何大写字母0次或多次,然后是一个空格,然后是(第二组)任何数字1次或多次。
So for SUNDAY 2
所以对于SUNDAY 2
Group 0: Entire match 小组0:整个比赛
Group 1: SUN 第一组:星期日
Group 2: 2 第2组:2
这个怎么样?:
^(\\w{3})\\D+(\\d+)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.