1

I have been trying to use a regexp that matches any text that is between a caret, less than and a greater than, caret.

So it would look like: ^< THE TEXT I WANT SELECTED >^

I have tried something like this, but it isn't working: ^<(.*?)>^

I'm assuming this is possible, right? I think the reason I have been having such a tough time is because the caret serves as a quantifier. Thanks for any help I get!

Update

Just so everyone knows, they following from am not i am worked

 /\^<(.*?)>\^/

But, it turned out that I was getting html entities since I was getting my string by using the .innerHTML property. In other words,

> ... &gt;
< ... &lt;

To solve this, my regexp actually looks like this:

\^&lt;(.*?)((.|\n)*)&gt;\^

This includes the fact that the string in between should be any character or new line. Thanks!

2
  • 3
    Caret not carrot :) Commented Jul 30, 2012 at 20:26
  • Thank you! I knew that couldn't be right! Commented Jul 30, 2012 at 21:08

2 Answers 2

4

You need to escape the ^ symbol since it has special meaning in a JavaScript regex.

 /\^<(.*?)>\^/

In a JavaScript regex, the ^ means beginning of the string, unless the m modifier was used, in which case it means beginning of the line.

Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

\^<(.*?)>\^

In a regex, if you want to use a character that has a special meaning (caret, brackets, pipe, ...), you have to escape it using a backslash. For example, (\w\b)*\w\. will select a sequence of words terminated by a dot.

Careful!

If you have to pass the regex pattern as a string, i.e. there's no regex literal like in javascript or perl, you may have to use a double backslash, which the programming language will escape to a single one, which will then be processed by the regex engine.
Same regex in multiple languages:

Python:
  import re
  myRegex=re.compile(r"\^<(.*?)>\^") # The r before the string prevents backslash escaping
PHP:
  $result=preg_match("/\\^<(.*?)>\\^/",$subject); // Notice the double backslashes here?
JavaScript:
  var myRegex=/\^<(.*?)>\^/,
      subject="^<blah example>^";
  subject.match(myRegex);

If you tell us what programming language you're writing in, we'll be able to give you some finished code to work with.

Edit: Whoops, didn't even notice this was tagged as javascript. Then, you don't have to worry about double backslash at all.

Edit 2: \b represent a word boundary. Though I agree yours is what I would have used myself.

1 Comment

A sequence of words terminated by a dot? I think you meant (\w+\s+)*\w+\.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.