code_junkie

Regex to find an integer within a string

Nov 13th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. Pattern intsOnly = Pattern.compile("\d*");
  2. Matcher makeMatch = intsOnly.matcher("dadsad14 dssaf jfdkasl;fj");
  3. makeMatch.find();
  4. String inputInt = makeMatch.group();
  5. System.out.println(inputInt);
  6.  
  7. "\d+"
  8.  
  9. unescaped: ([+-]?d+)([eE][+-]?d+)?
  10. escaped: ([\+-]?\d+)([eE][\+-]?\d+)?
  11.  
  12. unescaped: ([+-]?d(.d*)?|.d+)([eE][+-]?(d(.d*)?|.d+))?
  13. escaped: ([\+-]?\d(\.\d*)?|\.d+)([eE][\+-]?(\d(\.\d*)?|\.\d+))?
  14.  
  15. public T[] GetMatches<T>(string Input, string MatchPattern) where T : IConvertible
  16. {
  17. List<T> MatchedValues = new List<T>();
  18. Regex MatchInt = new Regex(MatchPattern);
  19.  
  20. MatchCollection Matches = MatchInt.Matches(Input);
  21. foreach (Match m in Matches)
  22. MatchedValues.Add((T)Convert.ChangeType(m.Value, typeof(T)));
  23.  
  24. return MatchedValues.ToArray<T>();
  25. }
  26.  
  27. string Test = "22$data44abc";
  28. string[] Matches = this.GetMatches<string>(Test, "\d+");
Add Comment
Please, Sign In to add comment