Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

Dart - Split String with Regex and keep the delimiter

I have following string :

final String text = """
This is first text <link="www.stackoverflow.com">First Hello</link>
This is the second text <link="www.stackoverflow.com">Second</link>
"""

I wanted to split the string and get the following result :

[
"This is first text ", 
"<link="www.stackoverflow.com">First Hello</link>", 
"This is the second text ", 
"<link="www.stackoverflow.com">Second</link>"
]

I tried using this regex but it's not as expected :

(?<=<link=".*">)|(?=</link>)

This is the result :

enter image description here

Can i split like this using Regex and how is the regex format?

Thank you.

question from:https://stackoverflow.com/questions/65915499/dart-split-string-with-regex-and-keep-the-delimiter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're close. Try:

var re = RegExp(r'(?=<link=".*?">)|(?<=</link>)');

It has two differences from your RegExp:

  • It swaps the (?= and (?<= because you want a split before a <link...>, so you want a lookahead for that, and after a </link>, so a lookbehind for that.
  • I added the ? to ".*?", because otherwise it could potentially match until a later " on the same line, instead of the first one. Your example didn't have that, but better safe than sorry.

With that, you get the strings:

  1. "This is first text "
  2. "<link="www.stackoverflow.com">First Hello</link>"
  3. " This is the second text "
  4. "<link="www.stackoverflow.com">Second</link>"
  5. " "

If you don't want the newlines to be included, you should probably remove them first.

if you want to combine the with the </link>, you can change the RegExp to

var re = RegExp(r'(?=<link=".*?">)|(?<=</link>
*(?<=
))');

That gives you:

  1. "This is first text "
  2. "<link="www.stackoverflow.com">First Hello</link> "
  3. "This is the second text "
  4. "<link="www.stackoverflow.com">Second</link> "

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...