简体   繁体   English

正则表达式从javascript中的字符串中获取前3个字母和所有数字

[英]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 2WEDNESDAY 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 2WED 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

You can do 你可以做

^(\w{3})\S+\s+(\d{1,2})

Demo 演示版

这个怎么样?:

^(\\w{3})\\D+(\\d+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正则表达式JavaScript-如何检查字符串是否全是字母,然后是所有数字 - Regex JavaScript - how to check if a string is all letters and then all numbers Javascript删除字符串中不是数字,字母和空格的所有字符 - Javascript remove all characters from string which are not numbers, letters and whitespace Javascript RegEx将所有单词提取为单个匹配项,但不从字符串中提取数字 - Javascript RegEx extract all words as single matches but not numbers from a string javascript正则表达式仅数字和字母 - javascript regex Numbers and letters only JavaScript正则表达式拆分数字和字母 - JavaScript regex to split numbers and letters 如何使用regex使用javascript来获取所有数字,然后是字符串标识符的第一位数字? - How do I use regex to take all numbers followed by the first digit of the identifier of a string using javascript? javascript字符串:删除数字和第一个“。”以外的所有字符 - javascript string: remove all except numbers and the first “.” Javascript + REGEX从字符串中获取第一个非零数字 - Javascript + REGEX to get first non-zero number from a string 使用正则表达式(javascript)检查字符串中的所有字母是否为辅音 - Use regex (javascript) to check if all letters in a string are consonants Javascript:如何获取字符串中的前4个数字? - Javascript: How to get the first 4 numbers in a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM