最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex date format for dash or forward slash - Stack Overflow

programmeradmin2浏览0评论

I have a regex which finds a string pattern of any of the following formats

28.05.2018 SB RS CS  
28-05-2018 SB RS CS  
28/05/2018 SB RS CS

The regular expressions matches the first example with the full stops in the date, but does not match the second and third example with the dashes and forward slashes in the date.

Can any one please advise how to correct the regular expression so that it matches a dash or a forward slash?

Any assistance will be most appreciated.

The script is part of an Adobe javascript.

var re = new RegExp(
"\\d{1,2}[\\-\\/\\.]\\d{1,2}[\\-\\/\\.]\\d{2,4}\\s([A-Z]{2,5})\\s([A-Z]{2,5})\\s([A-Z]{2,5})"
);

I have a regex which finds a string pattern of any of the following formats

28.05.2018 SB RS CS  
28-05-2018 SB RS CS  
28/05/2018 SB RS CS

The regular expressions matches the first example with the full stops in the date, but does not match the second and third example with the dashes and forward slashes in the date.

Can any one please advise how to correct the regular expression so that it matches a dash or a forward slash?

Any assistance will be most appreciated.

The script is part of an Adobe javascript.

var re = new RegExp(
"\\d{1,2}[\\-\\/\\.]\\d{1,2}[\\-\\/\\.]\\d{2,4}\\s([A-Z]{2,5})\\s([A-Z]{2,5})\\s([A-Z]{2,5})"
);
Share Improve this question edited Jun 1, 2018 at 0:45 Hunter McMillen 61.6k25 gold badges123 silver badges176 bronze badges asked Jun 1, 2018 at 0:44 JoJoJoJo 1253 silver badges10 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

You can use the following regex:

\d{1,2}[/.-]\d{1,2}[/.-]\d{2,4}\s([A-Z]{2,5})\s([A-Z]{2,5})\s([A-Z]{2,5})

demo

Notes:

You were really close, in a character class you do not need to escape the dash (if you put it at the end of the class definition) and the dot.

console.log("test 28.05.2018 SB RS CS test 28-05-2018 SB RS CS abc 28/05/2018 SB RS CS 123".match(/\d{1,2}[/.-]\d{1,2}[/.-]\d{2,4}\s([A-Z]{2,5})\s([A-Z]{2,5})\s([A-Z]{2,5})/g));

  String formateDateOfBirth(String? dob) {
    return '$dob'.replaceAllMapped(
        RegExp(r'(\d{2})(\d{2})'), (Match m) => '${m[1]}/${m[2]}');
  }

This will give with "mm/dd" formatting for month and day. eg: 01/25 You can customize also MM/dd/yyyy or any yyyy-MM-dd as per requirement.

发布评论

评论列表(0)

  1. 暂无评论