RegEx does not find all matches

I have the following code (AS3 and CS 5.5):

var regEx:RegExp = new RegExp(/(?:^|\s)(\#[^\s$]+)/g); var txt:String = "This #asd is a test tweet #hash1 test #hash2 test"; var matches:Object = regEx.exec(txt); trace(matches); 

Tracing returns '# asd, # asd'. I really don’t understand why this would be the case as in my RegEx test application "RegExhibit" it returns "# asd, # hash1, # hash2", as I expected. Can someone shed some light on this, please?

Thanks in advance!

+4
source share
1 answer

If you use .exec , you must run it several times to get all the results:

In the following example, the g (global) flag is set in the regular expression, so you can use exec () several times to find multiple matches:

 var myPattern:RegExp = /(\w*)sh(\w*)/ig; var str:String = "She sells seashells by the seashore"; var result:Object = myPattern.exec(str); while (result != null) { trace (result.index, "\t", result); result = myPattern.exec(str); } 

Source: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/RegExp.html

A better alternative is probably to use String.match :

If the pattern is a regular expression, to return an array with more than one matching substring, the g (global) flag must be set in the regular expression

An example should be (not verified):

 var regEx:RegExp = /(?:^|\s)(\#[^\s$]+)/g; var txt:String = "This #asd is a test tweet #hash1 test #hash2 test"; var matches:Object = txt.match(regEx); 
+6
source

Source: https://habr.com/ru/post/1387731/


All Articles