Zhang
Zhang

Reputation: 3356

Use regex to attach a '.' for each sequential Upper Case char

I Foo bar DNA

I want to replace DNA with D.N.A (D.N.A. also is ok), but not to replace 'I' and 'Foo'.

I have some clues, but they all failed.

string s = "I Foo bar DNA";
cout << std::regex_replace(s, std::regex("([A-Z]){2,}"), "$1.") << endl;
//output: I Foo bar A.

or

cout << std::regex_replace(s, std::regex("([A-Z])[A-Z]"), "$1.") << endl;
//output: I Foo bar D.A

Upvotes: 1

Views: 57

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You may use

([A-Z])(?=[A-Z])

Replace with $1..

See the regex demo

Here,

  • ([A-Z]) - matches and captures into Group 1 any ASCII uppercase letter
  • (?=[A-Z]) - the lookahead makes sure there is an ASCII uppercase letter after the previous one, but keeps the matched char outside of the overall match value.

C++ demo:

std::string s("I Foo bar DNA");
std::regex reg("([A-Z])(?=[A-Z])");
std::cout << std::regex_replace(s, reg, "$1.") << std::endl;
// => I Foo bar D.N.A

Upvotes: 5

Related Questions