我正在使用命名的捕获组来验证和提取产品编号中的数据。产品编号的格式如下:
public class MainActivity extends AppCompatActivity {
private WeirdFragment weirdFragment;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
}
public void openFragment(View v){
weirdFragment = new WeirdFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, weirdFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
我当前的代码如下:
1102961D048.075
Chars 1-2 gender_code 11
Chars 1-6 style 110296
Chars 7-8 width_code 1D
Chars 9-11 color_code 048
Char 12 delimiter ignored
Chars 13-15 size_code 075
由于const validateMpn = (mpn) => {
const regex = /(?<style>\d{6})(?<width>\d{1}[ABDE])(?<color_code>\d{3})\.(?<size_code>\d{3})/gi
const match = regex.exec(mpn)
if (!match) {
return null
}
return match.groups
}
const str1 = '1102961D048.075'
const str2 = '1200322A001.085'
const match1 = validateMpn(str1)
const match2 = validateMpn(str2)
console.log(match1)
console.log(match2)
和gender_code
重叠,因此我不确定如何同时获得它们。因此,我有以下问题:
答案 0 :(得分:3)
好的,只需将name
放在mysqli_fetch_field_direct($export, $i)->name
组内:
gender
答案 1 :(得分:1)
我建议对前两个和后四个字符使用单独的捕获组。然后,只需将前两个捕获组连接在一起即可形成style
:
var input = "1102961D048.075";
var regex = /(.{2})(.{4})(.{2})(.{3}).(.{3})/g;
var match = regex.exec(input);
console.log("gender_code: " + match[1]);
console.log("style: " + match[1] + match[2]);
作为样式说明,我更喜欢不使用命名捕获组,因为它们会导致难以理解的膨胀正则表达式。
答案 2 :(得分:1)
是的,您可以使用此正则表达式以积极的眼光捕捉性别代码,
(?=(..))(\d{6})(\d{1}[ABDE])(\d{3})\.(\d{3})
This is named groups regex but will only work in Chrome browser
和命名捕获分组将在ECMAScript 2018中可用,并且目前仅在Chrome中受支持。
此JS演示将在Chrome中运行,因为这是目前唯一支持EcmaScript2018的演示,
const validateMpn = (mpn) => {
const regex = /(?=(?<gender_code>\d\d))(?<style>\d{6})(?<width>\d{1}[ABDE])(?<color_code>\d{3})\.(?<size_code>\d{3})/gi
const match = regex.exec(mpn)
if (!match) {
return null
}
return match.groups
}
const str1 = '1102961D048.075'
const str2 = '1200322A001.085'
const match1 = validateMpn(str1)
const match2 = validateMpn(str2)
console.log(match1)
console.log(match2)