Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use regex to find text NOT between two characters

I have a single string of words, in which each word is separated by a newline character. I've used RegEx replacements to insert '{' and '}' characters around common prefixes and suffixes. The result looks like this:

{con}descens{ion}
lumberjack
tim{ing}
{tox}{icity}
fish
{dis}pel

What I'm trying to figure out is how I can perform a RegEx replace on this string that will only match text not between the '{' and '}' characters. I have further replacements to make, and each time I do, I'll be placing the '{' and '}' characters around the matches; I just don't wan't previous replacements (or pieces thereof) to be matched when performing new replacements. I know how to match "not '{'", for example, but I don't know how to match "not between '{' and '}'"

To put it into perspective, an example next replacement operation here would be to to replace all 'n' characters with '7' characters. In this case, the first line of the string, "{con}descens{ion}", should become "{con}desce{7}s{ion}" and not "{co{7}}desce{7}s{io{7}}"; the other words would remain the same based on these criteria.

Any suggestions?

like image 280
RapierMother Avatar asked May 30 '14 06:05

RapierMother


People also ask

How do I not match a character in regex?

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

How do I remove a specific character from a string in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

How do you check if a string contains at least one character?

To check if a string contains at least one letter using regex, you can use the [a-zA-Z] regular expression sequence in JavaScript. The [a-zA-Z] sequence is to match all the small letters from a-z and also the capital letters from A-Z . This should be inside a square bracket to define it as a range.

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

Assuming your curly braces will always be balanced, you can use a Negative Lookahead here.

[a-zA-Z]+(?![^{]*\})

Note: This only matches characters of the A to Z range, if words will include whitespace or you have other characters that need to be allowed or unsure of the type of input, you can use a negated match here.

[^}]+(?![^{]*\})

Live demo

like image 200
hwnd Avatar answered Nov 15 '22 14:11

hwnd