Comic Sans MS Lover
Comic Sans MS Lover

Reputation: 1729

RegEx - How to allow whitespace only if there's other characters

I have the following RegEx:

(\\+)([\\w\\d]+)(=)(.+)

This should allow:

+[CharWords][Digits]=[Everything]

The second part (after the '=') should not allow whitespace characters to be there, unless there is a digit or word char.

I can't seem to achieve this. How can such a RegEx be built.

EDIT:

Here are valid examples:

+Valid123=Valid123
+123Valid=Valid 123
+Valid=This is Valid 14
+Valid=(This is Valid)

My question is how to avoid this:

Not Valid=whitespace

Upvotes: 0

Views: 402

Answers (3)

anubhava
anubhava

Reputation: 784998

Following regex should work for you:

^(\\+)(\\w+)(=)(\\s*\\S+\\s*)+$

Upvotes: 2

Pshemo
Pshemo

Reputation: 124215

  1. \w stands for "word character", usually [A-Za-z0-9_] so you don't need to add \d inside your class.
  2. ...not allow whitespace characters to be there, unless there is a digit or word char.

    try maybe this way ...=(\\s*\\w+)+, -> \\s*\\w+ will accept only strings that have zero or more whitespaces at start and 1 or more characters at end like "a", " ab", " c". (\\s*\\w+)+ will make regex to accept 1 or more of such tokens.

Upvotes: 2

Walls
Walls

Reputation: 4010

Try this: ^\+[\w\d]+=(\S+.*)$.

This matches your first piece, but the key is in the part after the =. It requires at least one NON space followed by anything (which allows spaces after the initial match of a not space), so +word123= testing would fail where +word123=testing 123 would pass. If the first char. after the = is a space, it isn't allowed. If the first char. is anything but a space, it should allow spaces and anything else after the fact.

If you need to change what can come after the initial word/digit/etc after the =, you simply insert a more complex set of rules in a () in place of the . in (\S+.*).

The testing can be seen here. You may have to tweak it a bit (escape java slashes, etc).

Upvotes: 1

Related Questions