Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - only allow a space or nothing after a match

Tags:

Hi I'm nearly new with this of Regex... so, maybe my problem it's easy but I can't find a solution!

I'm writing a regex pattern that looks into the user's writing and paint with another color the matches that is founded. I want for example to paint with another color, if the user write something like this:

foo()

the thing is that I DON'T want to paint that if the user writes something else after that, I mean if the user write only

"foo()" (or "foo() ")

then it's fine, I want to paint it, but if the user write

"foo()d" 

I don't want to paint that because is now well written for me.

I already wrote the regex pattern that match the "foo()" (or also with a dot in the middle, like "foo.foo()"), but I´m facing with that problem. I need to add something to my pattern that allow only a space, or nothing (if the user write something else after the ")" I don't want to match it.) This is my pattern:

[a-z]*\.?[a-z]*\(("[^"\r\n]*"|[-]?\b\d+[\.]?\d*\b)?\)

Thank you very much!

like image 227
gezequiel Avatar asked Apr 18 '12 14:04

gezequiel


People also ask

How do I match a character except space in regex?

You can match a space character with just the space character; [^ ] matches anything but a space character.

How do you specify a space in regex?

Find Whitespace Using Regular Expressions in Java The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.

What does \b mean in regex?

A word boundary \b is a test, just like ^ and $ . When the regexp engine (program module that implements searching for regexps) comes across \b , it checks that the position in the string is a word boundary.

What does \d mean in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).


2 Answers

David Brabant is close, but I think you actually want to try ending your regular expression with (?!\S) - this will mean you'll match anything not followed by a non-whitespace character. If you just want to match on spaces rather than whitespace, use (?![^ ]).

like image 66
Ade Stringer Avatar answered Oct 08 '22 05:10

Ade Stringer


Use negative look ahead:

(\w+)(\.*)(\(\))+(\s)*(?!.)

The important part for you in the regex above is: (\s)*(?!.)

(\s)* : followed by 0 or more white spaces (?!.) : and no other character

like image 29
David Brabant Avatar answered Oct 08 '22 06:10

David Brabant