diff src/luan/modules/RegexLuan.java @ 1777:e59349d53fec

optimize String.replace and regex.gsub
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 10 Aug 2023 16:24:20 -0600
parents 2f3a8f16f583
children
line wrap: on
line diff
--- a/src/luan/modules/RegexLuan.java	Fri Jul 28 11:53:03 2023 +0300
+++ b/src/luan/modules/RegexLuan.java	Thu Aug 10 16:24:20 2023 -0600
@@ -71,14 +71,16 @@
 		Utils.checkNotNull(s);
 		int max = n==null ? Integer.MAX_VALUE : n;
 		final Matcher m = pattern.matcher(s);
+		if( max <= 0 || !m.find() )
+			return new Object[]{ s, 0 };
 		if( repl instanceof String ) {
 			String replacement = (String)repl;
 			int i = 0;
 			StringBuffer sb = new StringBuffer();
-			while( i<max && m.find() ) {
+			do {
 				m.appendReplacement(sb,replacement);
 				i++;
-			}
+			} while( i<max && m.find() );
 			m.appendTail(sb);
 			return new Object[]{ sb.toString(), i };
 		}
@@ -86,7 +88,7 @@
 			LuanTable t = (LuanTable)repl;
 			int i = 0;
 			StringBuffer sb = new StringBuffer();
-			while( i<max && m.find() ) {
+			do {
 				String match = m.groupCount()==0 ? m.group() : m.group(1);
 				Object val = t.get(luan,match);
 				if( val != null ) {
@@ -94,7 +96,7 @@
 					m.appendReplacement(sb,replacement);
 				}
 				i++;
-			}
+			} while( i<max && m.find() );
 			m.appendTail(sb);
 			return new Object[]{ sb.toString(), i };
 		}
@@ -102,7 +104,7 @@
 			LuanFunction fn = (LuanFunction)repl;
 			int i = 0;
 			StringBuffer sb = new StringBuffer();
-			while( i<max && m.find() ) {
+			do {
 				Object[] args;
 				final int count = m.groupCount();
 				if( count == 0 ) {
@@ -119,7 +121,7 @@
 					m.appendReplacement(sb,replacement);
 				}
 				i++;
-			}
+			} while( i<max && m.find() );
 			m.appendTail(sb);
 			return new Object[]{ sb.toString(), i };
 		}