1

I'm trying to replicate a method mentioned on this page:

Split a string into an array of words, punctuation and spaces in JavaScript

For example:

var text = "I like grumpy cats. Do you?";
console.log(
  text.match(/\w+|\s+|[^\s\w]+/g)
)

Returns:

[
  "I",
  " ",
  "like",
  " ",
  "grumpy",
  " ",
  "cats",
  ".",
  " ",
  "Do",
  " ",
  "you",
  "?"
]

But instead of Javascript, I'm using Dart. I'm having a hard time finding examples of how this would work in Dart, especially in formatting the regex.

I've tried this, but it's not returning the punctuation and spaces:

dynamic textToWords(String text) {
  // Get an array of words, spaces, and punctuation for a given string of text.
  var re = RegExp(r"\w+|\s+|[^\s\w]+g");
  final words = text != null
      ? re.allMatches(text != null ? text : '').map((m) => m.group(0)).toList()
      : [];
  return words;
}

Any help is appreciated.

1 Answer 1

0

Remove the g from the end of your RegExp.

Also text will never be null since you declared it as a String, so there is no need for these null checks.

List<String> textToWords(String text) {
  // Get an array of words, spaces, and punctuation for a given string of text.
  var re = RegExp(r"\w+|\s+|[^\s\w]+");
  final words = re.allMatches(text).map((m) => m.group(0) ?? '').toList();
  return words;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Oh man, thanks for this help! It does exactly what I needed. This was wracking my brain for hours. I really appreciate it!
Almost works for me, but breaks up contractions. E.g., don't becomes don ' t
@buttonsrtoys sure but the original javascript implementation joe was trying to replicate works this way also. If you want to keep contractions together you have to update the first part of the regex before the first | to account for contractions. You could try for example RegExp(r"\w+('|\w)*|\s+|[^\s\w]+").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.