Reputation:
I'm trying to get numbers with words after a determined word with regex:
var text = 'SOME HUGE TEXT ARCHIVE: KxhASjx0000-4 SOME HUGH TEXT';
var reg = new RegExp('ARCHIVE:' + '.*?(\\d\\S*)', 'i');
var match = reg.exec(text);
output will be:
0000-4
And i need:
KxhASjx0000-4
How can i improve this regex?
I was trying to use the W
symbol, but didn't work:
.*?(\\d\w+\\S*)
Upvotes: 1
Views: 1088
Reputation: 503
You can try this if you know that "ARCHIVE" is there in all of the lines :
.*?ARCHIVE:\s?([\w ]+\s?\S*)
It checks for ARCHIVE: and then white space if any, then it reads the word associated with and another white space if any. After that it reads the required digit.
--> .? - Any character any number of times -->ARCHIVE:
--> s? - white space if any -->A numbered captured group -->[\w ]+ - any character in this class. --> \S - anything other than white space.
PS: Do not forget to escape the characters accordingly.
Upvotes: 2
Reputation: 784998
You can use this regex:
var reg = new RegExp('ARCHIVE:' + '.*?([a-z\\d]\\S*)', 'i');
Or better:
var reg = /ARCHIVE:.*?([a-z\d]\S*)/i;
Instead of matching till a digit \d
here we're matching upto [a-z\d]
which is a letter or a digit that gives us match KxhASjx0000-4
in matched group.
Output:
var match = reg.exec(text);
// ["ARCHIVE: KxhASjx0000-4", "KxhASjx0000-4"]
Upvotes: 0