简体   繁体   中英

regex to match repetitive text divided by hash character that can repeat multiple times in multi line string

i have the following regex i'm using with C#

^.*(#\w+?#.+?#.+?#.+?#.+?:).*$

I need to be able to extract the last occurrence of a specifically formatted string within a multi line string

The format can be :

#test12345-abc#slkjs3234-df#slkj23423#slkjdj2343:{asdf9230-232_jk233}

or

#test12345-abc#slkjs3234-df#slkj23423#slkjdj2343:

and could have the format appear 1 or more times and back to back see examples below:

Example 1:

jlkjlkjlkjlkj
lkjlkjlj lkjlkj  #test12345-abc#slkjs3234-df#slkj23423#slkjdj2343:{asdf9230-232_jk233}  lkjlj
slkjlj

Example 2:

jlkjlkjlkjlkj
lkjlkjlj lkjlkj #test12345-abc#slkjs3234-df#slkj23423#l23lkj22:{asdf9230-232_jk233} #test12345-abc#slkjs3234-df#slkj23423#Other:{asdf9230-232_jk233}  lkjlj
slkjlj

Example 3:

jlkjlkjlkjlkj
lkjlkjlj lkjlkj  #test12345-abc#slkjs3234-df#slkj23423#slkjdj2343:  lkjlj
slkjlj

Example 4:

jlkjlkjlkjlkj
lkjlkjlj lkjlkj #test12345-abc#slkjs3234-df#slkj23423#l23lkj22: #test12345-abc#slkjs3234-df#slkj23423#Other:  lkjlj
slkjlj

i'm struggling to find the proper regex that would look for both the examples and in the different positions in the examples ?? thanks

You can use

var result = Regex.Match(text, @"(?:#\w+(?:-\w+)?)+(?::{[\w-]+})?", RegexOptions.RightToLeft)?.Value;

See the regex demo . Note that the RegexOptions.RightToLeft option makes the regex engine search for a match from the end of the string, so you get the last match if there are more than one.

Details

  • (?:#\\w+(?:-\\w+)?)+ - one or more repetitions of
    • # - a # char
    • \\w+ - one or more word chars (letters, digits, underscores)
    • (?:-\\w+)? - an optional non-capturing group matching 1 or 0 occurrences of - and then 1+ word chars
  • (?::{[\\w-]+})? - an optional non-capturing group:
    • : - a colon
    • {[\\w-]+} - a { char, then one or more letters, digits, underscores or hyphens and then a } char.

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