Michael Choi
Michael Choi

Reputation: 630

Regex match NOT surrounded by white spaces

Context: I am building an interpreter for fun and need to implement a white space rule.

The rule is that regex must match plus "+" when NOT surrounded by spaces. Here is a sample text:

a+b c +d g+ h i + j x+y

The plus between a and b should match as well as between x and y. I am new to regular expressions; however, I have tried the following regex:

\+(?<!\s)(?!\s)

Which for me means,

\+         find all "+" matches
(?<!\s)   (neg look behind) that don't have spaces behind
(?!\s)     (neg look ahead) that don't have spaces ahead

However when I run this on regex101, I am only able to match the first plus between a and b.

I am not sure what I am doing incorrectly here. Advice is appreciated.

Upvotes: 1

Views: 1158

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

You can simply use \[a-zA-Z\]\+\[a-zA-Z\]

or if there are more characters around + then use

[a-zA-Z]+\+[a-zA-Z]+

Update : you can use (?<!\s)[+)-](?!\s) by moving the matching symbol between lookbehind and lookahead conditions

Upvotes: 2

Related Questions