views:

114

answers:

3

I have this sample text, which is retrieved from the class name on an html element:

rich-message err-test1 erroractive
rich-message err-test2 erroractive
rich-message erroractive err-test1
err-test2 rich-message erroractive

I am trying to match the "test1"/"test2" data in each of these examples. I am currently using the following regex, which matches the "err-test1" type of word. I can't figure out how to limit it to just the data after the hyphen(-).

/err-(\S*)/ig

Head hurts from banging against this wall.

A: 

You could try 'err-([^ \n\r]*)' - but are you sure that it is the regex that is the problem? Are you using the whole result, not just the first capture?

Lucas Jones
The only bit that I need is the text after "err-". I would like to do the match cleanly in a single regex expression instead of matching the entire word then stripping "err-" using an extra method. Sure, it would save time now but its still not fixing the problem.
Geuis
+3  A: 

From what I am reading, your code already works.

Regex.exec() returns an array of results on success.

The first element in the array (index 0) returns the entire string, after which all () enclosed elements are pushed into this array.

var string = 'rich-message err-test1 erroractive';
var regex = new RegExp('err-(\S*)', 'ig');
var result = regex.exec(string);

alert(result[0]) --> returns err-test1
alert(result[1]) --> returns test1
Aron Rotteveel
Bloody hell, I'm an idiot. I have been using .match() instead of .exec(). Thank you!
Geuis
A: 

The stuff after the - should be in the results array. The first item is all the matching text (e.g. "err-test1") and the next items are the matches from the capture parentheses (e.g. "test1").

myregex = /err-(\S*)/ig;
mymatch = myregex.exec("data with matches in it");
testnum = mymatch[1];

Here's a reference site.

brien