Ioannis K.
Ioannis K.

Reputation: 552

Java regex to remove leading and 'in word' asterisks

I'm looking for a regex to remove all trailing asterisks and all asterisks inside a word.

*He*llo* -> Hello* <br>
Thi*s *is* *a* t*est* -> This is* a* test*

Ending asterisks should be accepted.

I'm not really experienced with regexes. I know I can write a simple program that loops through each word of a string and remove trailing and 'in-word' asterisks - but I wonder whether my problem can be solved using a regex, or not.

Hope that you can help me. Thank you in advance.

Best regards, Ioannis K.

Upvotes: 2

Views: 2318

Answers (3)

Tomalak
Tomalak

Reputation: 338248

Replace

\**\b

with the empty string, globally.

Java uses strings to represent regular expressions, so you have to escape accordingly:

"\\**\\b"

Upvotes: 1

Betlista
Betlista

Reputation: 10549

    final String[] in = { "*He*llo*", "Thi*s is *a* t*est*" };
    for ( final String s : in ) {
        System.out.println( s.replaceAll( "\\*(\\b)", "$1" ) );
    }

Upvotes: 1

Jerome Cance
Jerome Cance

Reputation: 8183

You need to use look ahead.

Take a look here : http://www.regular-expressions.info/lookaround.html

This is something like : \*(?!( |$))

This regex says : delete all * which are not followed by a space or the end of the line. (not tested)

Upvotes: 2

Related Questions