嘿那里,我正在尝试对字符串执行向后正则表达式搜索,将其划分为3位数组.从AS3 文档中我可以看到,在reg ex引擎中无法向后搜索.
这个练习的目的是将三元组逗号插入到这样的数字中:
10000000 => 10,000,000
我想这样做:
string.replace(/(\d{3})/g, ",$1")
但这是不正确的,因为搜索没有从后面发生,替换$ 1只适用于第一场比赛.
我感觉我会更好地使用循环执行此任务.
更新:
由于AS3不支持前瞻,这就是我解决它的方法.
public static function formatNumber(number:Number):String { var numString:String = number.toString() var result:String = '' while (numString.length > 3) { var chunk:String = numString.substr(-3) numString = numString.substr(0, numString.length - 3) result = ',' + chunk + result } if (numString.length > 0) { result = numString + result } return result }
toolkit.. 48
如果您的语言支持正面预测断言,那么我认为以下正则表达式将起作用:
(\d)(?=(\d{3})+$)
在Java中演示:
import static org.junit.Assert.assertEquals; import org.junit.Test; public class CommifyTest { @Test public void testCommify() { String num0 = "1"; String num1 = "123456"; String num2 = "1234567"; String num3 = "12345678"; String num4 = "123456789"; String regex = "(\\d)(?=(\\d{3})+$)"; assertEquals("1", num0.replaceAll(regex, "$1,")); assertEquals("123,456", num1.replaceAll(regex, "$1,")); assertEquals("1,234,567", num2.replaceAll(regex, "$1,")); assertEquals("12,345,678", num3.replaceAll(regex, "$1,")); assertEquals("123,456,789", num4.replaceAll(regex, "$1,")); } }
以下链接表明AS3有吗?
如果您的语言支持正面预测断言,那么我认为以下正则表达式将起作用:
(\d)(?=(\d{3})+$)
在Java中演示:
import static org.junit.Assert.assertEquals; import org.junit.Test; public class CommifyTest { @Test public void testCommify() { String num0 = "1"; String num1 = "123456"; String num2 = "1234567"; String num3 = "12345678"; String num4 = "123456789"; String regex = "(\\d)(?=(\\d{3})+$)"; assertEquals("1", num0.replaceAll(regex, "$1,")); assertEquals("123,456", num1.replaceAll(regex, "$1,")); assertEquals("1,234,567", num2.replaceAll(regex, "$1,")); assertEquals("12,345,678", num3.replaceAll(regex, "$1,")); assertEquals("123,456,789", num4.replaceAll(regex, "$1,")); } }
以下链接表明AS3有吗?
在http://gskinner.com/RegExr/上找到
社区>数千个分隔符
图案: /\d{1,3}(?=(\d{3})+(?!\d))/g
更换: $&,
trace ( String("1000000000").replace( /\d{1,3}(?=(\d{3})+(?!\d))/g , "$&,") );
它完成了这项工作!
如果您的正则表达式引擎具有正向前瞻,您可以执行以下操作:
string.replace(/(\d)(?=(\d\d\d)+$)/, "$1,")
正向前瞻(?= ...)意味着正则表达式仅在前瞻表达式匹配时匹配.
(注意,环绕表达式并不总是很有效.)