Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

preg match - Regex: Specify "space or start of string" and "space or end of string"

Imagine you are trying to pattern match "stackoverflow".

You want the following:

 this is stackoverflow and it rocks [MATCH]

 stackoverflow is the best [MATCH]

 i love stackoverflow [MATCH]

 typostackoverflow rules [NO MATCH]

 i love stackoverflowtypo [NO MATCH]

I know how to parse out stackoverflow if it has spaces on both sites using:

/s(stackoverflow)s/

Same with if its at the start or end of a string:

/^(stackoverflow)s/

/s(stackoverflow)$/

But how do you specify "space or end of string" and "space or start of string" using a regular expression?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use any of the following:

      #A word break and will work for both spaces and end of lines.
(^|s)  #the | means or. () is a capturing group. 


/(stackoverflow)/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=s|$)          #to look ahead.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...