my string (str2) = "aaaabbaacc"

i wanted to parse out the two a groups. some trials had worked according to plan , while a few , are giving me outcomes i dont understand. im hoping the members could help me out :)

problematic regexp 1 : console.log(str2.match(/a+(a+(?=c))/).toString());
this gives "aa , a"

problematic regexp 2 : console.log(str2.match(/^a+(a+(?=c))/).toString());
this gives : Uncaught TypeError: Cannot call method 'toString' of null

no idea why the two works like the way they do. i was expecting both to give "aaaa , aa" as the result !

Regex 1 checks for any number of a's followed by a c.

Regex 2 does the same, but expects the a to start at the beginning of the line, which won't match any substring.

checks for any number of a's followed by a c.

but i have the lookahead part under parens , why doesnt the one on the outside return 4-a's ?

Because the regex expects to end with a c. You don't allow any other characters in between, or you haven't specified them.

can you give an example of this putting things in between ? i just learned this today...

a+      One or more a
(a+     One or more a
(?=c))  Followed by a c

You only specified to recognize a's and c's. If you wish to capture the first part of your string too, you could try this:

a+(a+(?=b|c))

// this is similar, capturing the a's separately.
(a+)(b|c)

The problem is that I'm not sure what you are trying to capture. Is this anything specific?

regarding the null error of exp2 , i suppose that the whole pattern resulting from the regex , the (compiler ? ) wants to find it at the start , which not being there , gives a null. i read that regexps are evaluated left to right , so i thought ^a+ would be evaluated first , and that would give "aaaa"...

edit : didnt see you already posted above..

a+(a+(?=b|c))

ahh ! so thats what i was doing wrong ! thanks for pointing that out :)

the ^ means to start searching from the beginning, that's correct. However, the rest of your pattern does not match your string (because those a's don't end with a c), so null is returned.

^ means to start searching from the beginning,

how is ^a different from \b ? that should also let me start from the begining right ?

^ indicates start of a string

\b indicates a word boundary (beginning/end of string, spaces, white space characters and more)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.