简体   繁体   中英

Regular expression for match

How to find such lines in a file

########     this_is_a_line.sh     ######## 

I tried the below regular expression but it does not work

(#)+( )+(A-Za-z0-9_)+(.sh)( )+(#)+ 

But this doesn't seem to work. Can anyone let me know what is wrong?

You used (...) (a capturing group ) instead of [...] (a character class ). Use the character class:

#+ +[A-Za-z0-9_]+\.sh +#+
    ^^^^^^^^^^^^^

See regex demo (note most of the capture groups are redundant here, and I removed them. Also, . must be escaped to match a literal dot.)

The [A-Za-z0-9_]+ matches 1 or more letters, digits or _ .

The (A-Za-z0-9_)+ matches 1 or more sequences of A-Za-z0-9_ (see demo ).

Also, in Java, you can use \\w to match [A-Za-z0-9_] and shorten your regex to

#+ +\w+\.sh +#+

Do not forget that you need to double each \\ in the pattern string in Java ( String pattern = "#+ +\\\\w+\\\\.sh +#+"; ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM