2

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?

Viacheslav Dobromyslov
  • 3,168
  • 1
  • 33
  • 45
ChriS
  • 23
  • 1
  • 1
  • 3

3 Answers3

4

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].*

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • That works fine thanks, but is is there a way that the lines are moved up? So far when I replace it with nothing Textpad keeps the empty line. – ChriS Nov 05 '13 at 14:35
  • 2
    In that case, you'll want to match the trailing `\r\n` as well. Just add `(\r\n)?` to the end of the regex (made optional since the newline may be missing on the last line of the file). – Tim Pietzcker Nov 05 '13 at 16:38
1

try this

^(.*[#].*)$

Regular expression visualization

Debuggex Demo

or maybe

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

Regular expression visualization

Debuggex Demo

bukart
  • 4,906
  • 2
  • 21
  • 40
0

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
MadConan
  • 3,749
  • 1
  • 16
  • 27
  • This is essentially what my regex is doing, but with one problem: `\s` also matches a newline character, so the two lines `a #\nbc` would be matched/removed as well. – Tim Pietzcker Nov 05 '13 at 13:58