-1

^ specifies that the match must start at the beginning of a line or string.

What does string mean?

Does it mean /^(apple)/ will match this applesauce is delicious, as apple is beginning of the string applesauce.

Does ^ always have to be in the beginning of the search in regex engine?

Why isn't his matched /apple ^(his)/?

apple 
his

since his is in the beginning of the string?

Please escape the meaning of ^ in character sets.

user3942918
  • 23,357
  • 10
  • 50
  • 66
B Luthra
  • 173
  • 9
  • If `applesauce` is the string, what is `this applesauce is delicious`? [read more...](https://en.wikipedia.org/wiki/Substring) – bobble bubble Jun 08 '19 at 23:40

1 Answers1

0

No, ^ or \A is not always necessary for a regular expression. Sometimes we would include them in our expressions, if required, especially for validating strings.

In your example, this applesauce is delicious is the string, and ^(apple) will not match our string here, because our string does not start with apple, starts with this:

Demo 1

If we remove the start anchor, our expression would look like:

(apple)

which has a capturing group (), then that would find and capture apple in any part of our string.

Demo 2

If we add a word boundary to our expression, for instance:

(\bapple\b)

then, we would be only finding apple as a separate word, not as a part of a sub-string, if you will, thus we would not capture applesauce.

Demo 3

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Difference between line and string

String refers to the entire input to our expression, which may be only one line or may consist of several lines (such as a paragraph). For instance, this is considered a string, which has multiple lines:

this applesauce is delicious this applesauce is delicious
apple is delicious apple is delicious

apple is delicious

apple is delicious

apple is delicious

Demo 4

Great Question

In the last question, apple ^(his) will not match:

apple 
his

because there is a new line between apple and his, yet an space ( ) or \s is not sufficient, however

apple\s*^(his)

will match that, since \s* passes both space and new lines as well, even though ^ may not be necessary there.

Demo 5

Community
  • 1
  • 1
Emma
  • 1
  • 9
  • 28
  • 53
  • 2
    then what's the difference between line and a string? – B Luthra Jun 08 '19 at 23:37
  • 1
    Can you just answer one last question for now? why wasn't "his" matched or /apple ^(his)/ trying to search for? – B Luthra Jun 08 '19 at 23:59
  • 1
    https://regex101.com/r/kWBtoM/2 – B Luthra Jun 09 '19 at 00:04
  • Since your answer was pretty good can you help me by providing me solution.It was marked duplicate but that post didn't solve all my queries .Look at this post when you are free https://stackoverflow.com/questions/56514834/word-boundaries-in-regex – B Luthra Jun 09 '19 at 19:45