AD.Net
AD.Net

Reputation: 13409

Regex match and replace

I need to match only the start of string like these with mainly pattern in "KEYWORD AAA/0010/0 " with a space after /0 and replace it with any other string. It has to happen for only the instance in the start.

KEYWORD AAA/0010/0 
KEYWORD AAAAAA/0010/0
KEYWORD AAA/001000/0
KEYWORD AAA/0010/000
KEYWORD AAA/0010/0 Testing comment
KEYWORD AAA/0010/0 Testing comment KEYWORD AAA/0010/0 Testing comment
KEYWORD */*/*
KEYWORD ?/?/?

I have tried this but it does not distinguish between the instances at start and middle and it does not match the last one

^KEYWORD .*\/.*\/.*\s

Any help would be highly appreciated.

Upvotes: 0

Views: 105

Answers (3)

stema
stema

Reputation: 93046

What about

^KEYWORD [^\s/]*\/[^\s/]*\/[^\s/]*(?:\s|$)

See it here on Regexr

The last row is not matched, because there is no space following, therefore I replaced it by Whitespace or the end of the string (?:\s|$).

Upvotes: 1

FixMaker
FixMaker

Reputation: 3877

I think you're almost there. Your regex isn't matching your last test case because there isn't a space at the end. Try this instead:

/^KEYWORD .*\/.*\/.*(\s|$)/

Upvotes: 1

Wrikken
Wrikken

Reputation: 70540

Ungreedy .*?'s (match until next /, or even [^/]*), and optional \s with \s? (for the last line), making ^KEYWORD .*?\/.*?\/.*?\s? or ^KEYWORD [^\/]*\/[^\/]*\/[^\/]*\s?

Upvotes: 1

Related Questions