Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression: match only non-repeated occurrence of a character

Tags:

regex

I need to find and replace all occurrences of apostrophe character in a string, but only if this apostrophe is not followed by another apostrophe.

That is

abc'def

is a match but

abc''def

is NOT a match.

I've already composed a working pattern - (^|[^'])'($|[^']) but I believe it may be shorter and simpler.

Thanks,

Valery

like image 451
ValeryC Avatar asked May 20 '11 09:05

ValeryC


People also ask

What does regex (? S match?

Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What is the regular expression matching one or more specific characters?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .

What is escaped character in regex?

The \ is known as the escape code, which restore the original literal meaning of the following character. Similarly, * , + , ? (occurrence indicators), ^ , $ (position anchors) have special meaning in regex. You need to use an escape code to match with these characters.

How do you repeat in regex?

A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.


2 Answers

depends on your environment - if your environment supports lookahead and lookbehind, you can do this: (?<!')'(?!')

Ref: http://www.regular-expressions.info/lookaround.html

like image 169
Tao Avatar answered Oct 02 '22 10:10

Tao


I think your pattern is short and precise. You could be using negative lookahead/lookbehind, but they would make it a lot more complex. Maintainability is important.

like image 44
jwueller Avatar answered Oct 02 '22 08:10

jwueller