Home > Net >  How to extract alphanumeric word from string in dart?
How to extract alphanumeric word from string in dart?

Time:10-23

I have a string like as follows.

var string = "My id is 6aT7u. I used to play basketball and cricket.";

I have to extract the ID, i.e an alphanumeric word, using a regex. I have to extract 6aT7u in this case.

I tried [a-zA-Z0-9] but this doesn't work.

CodePudding user response:

You can use

\b(?:\d [A-Za-z]|[A-Za-z] \d)[a-zA-Z0-9]*\b

See the regex demo. Details:

  • \b - a word boundary
  • (?:\d [A-Za-z]|[A-Za-z] \d) - a non-capturing group matching either
    • \d [A-Za-z] - one or more digits and then an ASCII letter
    • | - or
    • [A-Za-z] \d - one or more ASCII letters and then a digit
  • [a-zA-Z0-9]* - zero or more ASCII digits or letters
  • \b - a word boundary.

Gettting the first match in Dart can be done with a code like

var string = "My id is 6aT7u. I used to play basketball and cricket.";
  var rx = RegExp(r'\b(?:\d [A-Za-z]|[A-Za-z] \d)[a-zA-Z0-9]*\b');
  var match = rx.firstMatch(string);
  if (match != null) {
    print(match.group(0));
  }
// => 6aT7u
  • Related