/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] naughty regular expressions!

Hey folks,

I’m having a spot of trouble with a regular expression or two. In general, I’m trying to search/replace certain acronyms and abbreviations with their whole-word equivalents. So, for example, the following is one of my current replacements:

[code=php]$n = preg_replace(“/bsch{0,1}.{0,1}b/i”, “School”, $n);[/code]

However, the regular expression ignores the period in “[I]ABC Sch.[/I]” and produces “[I]ABC School.[/I]” (unacceptable).

[B]{0,1}[/B] [I]should[/I] be performing greedy matching on the period. However, it doesn’t appear to work [U]as [B]I[/B] had initially expected it to[/U] near a word boundary marker (since the period itself is a word boundary marker, I suppose). If anyone could offer any suggestions, that would be great.

Thanks!

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@svidgenauthorAug 26.2009 — ... Nevermind. Looks like I got it.
[code=php] $n = preg_replace("/bsch{0,1}(.|b)/i", "School", $n); [/code]

My logical error in thinking I could match a word-boundary next to a non-word character kept me off-course for awhile ... But, the above solution works, for those interested.
Copy linkTweet thisAlerts:
@NogDogAug 26.2009 — [Oops...posted in wrong thread.]
Copy linkTweet thisAlerts:
@TeufelAug 27.2009 — For the future:

You can just use a ? to mark if a character can appear:

/foo?bar/.test("foobar"); // returns true

/foo?bar/.test("fobar"); // also true

The second o is "maybe"
Copy linkTweet thisAlerts:
@svidgenauthorAug 27.2009 — Yes--The issues arose in trying to match a non-word character (a period) next to a word boundary. The period is always excluded from the match, which will prevent it from being replaced by [I]<insert your programming language's replacement function/syntax here>[/I].
×

Success!

Help @svidgen spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...