Nauman Bashir
Nauman Bashir

Reputation: 1752

matching the regular expression with the whole string

im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

/\\^^\\w+\\$^/

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???

Upvotes: 4

Views: 8541

Answers (6)

Andreas Wong
Andreas Wong

Reputation: 60594

Try

/^\^\s*(\w+\s*)+\^$/

Upvotes: 0

Toto
Toto

Reputation: 91518

Here is a way to do the job:

$strs = array('^hello world^', 'my ^hello world^');
foreach($strs as $str) {
    echo $str, preg_match('/^\^.*\^$/', $str) ? "\tmatch\n" : "\tdoesn't match\n";
}

Output:

^hello world^   match
my ^hello world^        doesn't match

Upvotes: 5

Emiliano M.
Emiliano M.

Reputation: 241

Another pattern is: ^\^[^\^]*\^$ if you want match "^hello world^" and not "hello ^world^" , while \^[^\^]*\^ if you want match "^hello world^" and world in the "hello ^world^" string.

For Will: ^\^.*\^$ this match also "^hello^wo^rld^" i think isn't correct.

Upvotes: 0

codaddict
codaddict

Reputation: 455470

You can use the regex:

^\^[\w\s]+\^$

^ is a regex meta-character which is used as start anchor. To match a literal ^ you need to escape it as \^.

So we have:

  • ^ : Start anchor
  • \^: A literal ^
  • [\w\s]+ : space separated words.
  • \^: A literal ^
  • $ : End anchor.

Ideone Link

Upvotes: 2

Will
Will

Reputation: 3680

Actually, ^\^\w+\^$ will not match "^hello world^" because you have two words there; the regex is only looking for a single word enclosed by "^"s.

What you are looking for is: ^\^.*\^$ This will match "^^", "^hello world^", "^a very long string of characters^", etc. while not matching "hello ^world^".

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

Anchor the ends.

/^...$/

Upvotes: 6

Related Questions