Question

I am trying to find in Textpad a character with regex (for example "#") and if it is found the whole line should be deleted. The # is not at the beginnen of the line nor at the end but somewehre in between and not connected to another word, number or charakter - it stands alone with a whitespace left and right, but of course the rest of the line contains words and numbers.

Example:

My first line
My second line with # hash
My third line# with hash

Result:

My first line
My third line# with hash

How could I accomplish that?

Was it helpful?

Solution

Let's break it down:

^     # Start of line
.*    # any number of characters (except newline)
[ \t] # whitespace (tab or space)
\#    # hashmark
[ \t] # whitespace (tab or space)
.*    # any number of characters (except newline)

or, in a single line: ^.*[ \t]#[ \t].*

OTHER TIPS

try this

^(.*[#].*)$

Regular expression visualization

Debuggex Demo

or maybe

(?<=[\r\n^])(.*[#].*)(?=[\r\n$])

Regular expression visualization

Debuggex Demo

EDIT: Changed to reflect the point by Tim

This

public static void main(String[] args){
    Pattern p = Pattern.compile("^.*\\s+#\\s+.*$",Pattern.MULTILINE);

    String[] values = {
        "",
        "###",
        "a#",
        "#a",
        "ab",
        "a#b",
        "a # b\r\na b c"
    };
    for(String input: values){
        Matcher m = p.matcher(input);
        while(m.find()){
            System.out.println(input.substring(m.start(),m.end()));
        }

    }
}

gives the output

a # b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top