analyser
analyser

Reputation: 271

Regex to match a text with special chars in it

I need a regex to match a text with special chars -,.+\/& in it. The special chars must not be more than 2 subsequent and a special char can not be followed by space. More specifically I have to cover these cases:

some text/
/some text
some /text

I came up with this regex:

^[-\/,\.+\&]{0,1}[\p{L}]+[-\/,\.+\&]{0,1}([\s\-']?[-\/,\.+\&]{0,1}[\p{L}]+)([-\/,\.+\&]{0,1})$

It matches most of the cases that I need but fails to match for instance: some te&xt. Every help will be appreciated. Thanks.

Upvotes: 0

Views: 78

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You can use

"^(?!.*(?:[-,.+/&]\\s|[-,.+/&]{2}))[^\\s\\d]+(?:\\s+[^\\s\\d]+)*$"

See the regex demo

Explanation:

  • ^ - start of string
  • (?!.*(?:[-,.+/&]\\s|[-,.+/&]{2})) - a negative lookahead that fails the match if there is a special char [-,.+/&] followed with a whitespace \s, or 2 consecutive special chars from [-,.+/&] set
  • [^\\s\\d]+ - 1 or more characters other than digit and whitespace
  • (?:\\s+[^\\s\\d]+)* - 0+ sequences of:
    • \\s+ - 1+ whitespaces
    • [^\\s\\d]+ - 1 or more characters other than digit and whitespace
  • $ - end of string

Upvotes: 1

analyser
analyser

Reputation: 271

I found the solution:

^[-\/,\.+\&\s]{0,1}([\p{L}][-\/,\.+\&\s]{0,1})+([-\/,\.+\&\s]{0,1}([\p{L}][-\/,\.+\&\s]{0,1})+)([\p{L}][-\/,\.+\&\s]{0,1})([-\/,\.+\&\s]{0,1})$

Upvotes: 0

Related Questions