Question

I'm trying add a space before a particular string (Token for example) by replacing a regex with another: somethingToken should become something Token but something Token should stay something Token_ and not something Token (with 2 spaces)

I'm having trouble finding a regex that would match a non-space character and then the Token but without including the non-space character in the match (otherwise it would get replaced as well). A (failed) attempt was to try to negate a \b anchor (which should match the beginning of a word), but I don't know if I can negate an anchor. Any help on this is appreciated. Thanks.

Was it helpful?

Solution

I have just found the answer to this, perhaps it will be useful for someone else:

\BToken 

which represents a negated word boundary, so essentially matching wherever the standard word boundary (\b) does not match. For my example, it does indeed match somethingToken but not something Token which is left as is.

OTHER TIPS

In Java, this can be achieved as follows:

final String text = "fooToken foo Token";

// Prints 'foo Token foo Token'
System.out.println(text.replaceAll("(?<=\\S)(?=Token)", " "));

The concepts here are lookbehind and lookahead. See Regex Tutorial - Lookahead and Lookbehind zero-width assertions for more information.

(?<!\u0020)(?=Token)

This will look behind for a non-space, then will lookahead for Token, but have no width. This way you can replace this match with a space.

Edit: If you need it to work in Javascript, \u0020?(?=Token) Make a space optional, then you will replace the space with a space for no net change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top